加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

用于上传文件的Java HTTP客户端(multipart / form-data)

发布时间:2020-12-15 01:08:59 所属栏目:Java 来源:网络整理
导读:我正在尝试实现一个HTTP客户端,该客户端发出多部分请求以将文件上载到HTTP服务器. HTML表单有三个输入字段:一个用于用户名,一个用于密码,一个用于文件.服务器端如下所示. 我的实现如下. public class MultipartUploader { private static final String CHAR

我正在尝试实现一个HTTP客户端,该客户端发出多部分请求以将文件上载到HTTP服务器. HTML表单有三个输入字段:一个用于用户名,一个用于密码,一个用于文件.服务器端如下所示.

我的实现如下.

public class MultipartUploader {

    private static final String CHARSET = "UTF-8";

    private static final String CRLF = "rn";

    public String httpUpload(String url,String filename,byte[] byteStream)
        throws MalformedURLException,IOException {

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        final String boundary = Strings.repeat("-",15) + Long.toHexString(System.currentTimeMillis());

        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection","Keep-Alive");
        connection.setRequestProperty("Cache-Control","no-cache");
        connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);

        OutputStream directOutput = connection.getOutputStream();
        PrintWriter body = new PrintWriter(new OutputStreamWriter(directOutput,CHARSET),true);

        body.append(CRLF);
        addSimpleFormData("myuser","myUserName",body,boundary);
        addSimpleFormData("mypassword","mySecretPassword",boundary);
        addFileData("myfile",filename,byteStream,directOutput,boundary);
        addCloseDelimiter(body,boundary);

        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();

        String payload = CharStreams.toString(new InputStreamReader(connection.getInputStream()));
        return payload;
    }

    private static void addSimpleFormData(String paramName,String wert,PrintWriter body,final String boundary) {

        body.append(boundary).append(CRLF);
        body.append("Content-Disposition: form-data; name="" + paramName + """).append(CRLF);
        body.append("Content-Type: text/plain; charset=" + CHARSET).append(CRLF);
        body.append(CRLF);
        body.append(wert).append(CRLF);
        body.flush();
    }

    private static void addFileData(String paramName,byte[] byteStream,OutputStream directOutput,final String boundary) throws IOException {

        body.append(boundary).append(CRLF);
        body.append("Content-Disposition: form-data; name="" + paramName + ""; filename="" + filename + """)
            .append(CRLF);
        body.append("Content-Type: application/octed-stream").append(CRLF);
        body.append("Content-Transfer-Encoding: binary").append(CRLF);
        body.append(CRLF);
        body.flush();

        directOutput.write(byteStream);
        directOutput.flush();

        body.append(CRLF);
        body.flush();
    }

    private static void addCloseDelimiter(PrintWriter body,final String boundary) {

        body.append(boundary).append("--").append(CRLF);
        body.flush();
    }
}

服务器响应200 OK.我遇到的问题是,不正确地创建了HTTP正文,以便我从服务器获得的响应表明并非所有表单字段都已设置.服务器没有说明它是哪个字段.
所以我的问题是你看到这个代码有什么问题吗?我是否正确创建了多部分请求?

我还尝试使用cURL上传一个文件,并使用以下命令.

cURL -F "myuser=myUserName" -F "mypassword=mySecretPassword" -F "myfile=@/path/to/my/file.zip" "http://abcdef.gh:1234/path/to/uploader"
最佳答案
您在数据部分之间的界限在开头缺少额外的两个破折号: –

我通过捕获通过程序制作的http://httpbin.org/post请求并卷曲并通过diff工具进行比较来找到这个.我使用Wireshark来捕获请求.

以下是解决此问题的方法:

private static void addSimpleFormData(String paramName,final String boundary) {

    body.append("--").append(boundary).append(CRLF);
    body.append("Content-Disposition: form-data; name="" + paramName + """).append(CRLF);
    body.append("Content-Type: text/plain; charset=" + CHARSET).append(CRLF);
    body.append(CRLF);
    body.append(wert).append(CRLF);
    body.flush();
}

private static void addFileData(String paramName,final String boundary) throws IOException {

    body.append("--").append(boundary).append(CRLF);
    body.append("Content-Disposition: form-data; name="" + paramName + ""; filename="" + filename + """)
            .append(CRLF);
    body.append("Content-Type: application/octed-stream").append(CRLF);
    body.append("Content-Transfer-Encoding: binary").append(CRLF);
    body.append(CRLF);
    body.flush();

    directOutput.write(byteStream);
    directOutput.flush();

    body.append(CRLF);
    body.flush();
}

private static void addCloseDelimiter(PrintWriter body,final String boundary) {
    body.append("--").append(boundary).append("--").append(CRLF);
    body.flush();
}

注意每个方法开头的额外.append(“ – ”).

有关完整的工作代码,请参阅https://gist.github.com/shtratos/8e9570a4a5591b2bcecd55ca60b3f24f

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读