【发布时间】:2014-07-11 06:54:52
【问题描述】:
我正在使用 HttpClient 4.3.3。我的任务是将文件上传到服务器上。 以下是我的代码:
InputStream inputStream = new FileInputStream(new File("/path/to/file"));
byte[] data;
data = IOUtils.toByteArray(inputStream);
InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data),"file-name-on-ser");
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("file",inputStreamBody);
HttpPost httpPost = new HttpPost("file upload URL");
httpPost.setEntity(multipartEntity.build());
CloseableHttpResponse response = httpclient.execute(httpPost);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null)
{
System.out.println(line);
}
当我运行此代码时,它成功连接到服务器。但是响应的输出是
<html>
<head><title>411 Length Required</title></head>
<body bgcolor="white">
<center><h1>411 Length Required</h1></center>
<hr><center>server-name</center>
</body>
</html>
当我使用 firebug 进行调试时,我看到以下请求标头。
响应标头视图来源
Cache-Control 无存储,无缓存
连接保持活动
2014 年 5 月 22 日星期四 08:58:02 GMT
保持活动超时=30
服务器 *****
Set-Cookie **** 路径=/
传输编码分块
请求标头查看源代码
接受 text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
接受编码 gzip,放气
Accept-Language en-US,en;q=0.5
连接保持活动
饼干****
主机*****
参考 https://****/shareupload/
用户代理 Mozilla/5.0 (Windows NT 6.1; rv:29.0) Gecko/20100101 Firefox/29.0
从上传流中请求标头
内容长度 12642
Content-Type multipart/form-data;边界=---------------105143784893
我看到过类似的堆栈溢出问题。
2)File upload using apache's httpclient library not working
但我仍然无法找到解决问题的方法。 是否需要在请求头中设置 Content-Length 和 Content-Type 参数?
提前谢谢你。
【问题讨论】:
-
我找到了stackoverflow.com/questions/10161578/…。这可以帮助解决问题。
标签: apache apache-httpclient-4.x