Java中的MultipartEntityBuilder HttpPost套接字写入错误

时间:2016-02-17 07:25:44

标签: java file-upload http-post multipartentity httppostedfilebase

我正在尝试使用java中的httpPost请求(通过MultipartEntityBuilder)上传文件。但我得到软件导致连接中止:套接字写入错误

这是我的httpPost主体(在wireShark中)

------WebKitFormBoundaryWphJNFngxYSpEvNO
Content-Disposition: form-data; name="csrf_token"

csrf:sjwzV6dOZaNFwc0jWVrNNcFvhM7uv3BK00vZ0hCgEUzi2cG7r7Arx0Q3UZKlXeaR
------WebKitFormBoundaryWphJNFngxYSpEvNO
Content-Disposition: form-data; name="imagefilename"; filename="myfile.bin"
Content-Type: application/octet-stream

²qz‹ÁOOõMÓâg‘Ç`:----This area is file's binary code------Êëá‡/oåup

代码方是:

            File file = new File(filePath);
            String message = csrf_token;
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.addBinaryBody("imagefilename", file, ContentType.DEFAULT_BINARY, file.getName());
            builder.addTextBody("csrf_token", message, ContentType.DEFAULT_BINARY);
//
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);

和错误:

enter image description here

有什么想法吗?谢谢大家。

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,这些链接对回答非常有用

here是带有http客户端示例的文件上载

使用httpUrlConnection

here也是fileupload