利用 HttpClient 上传文件
2018-07-20 来源:open-open
最近的工作需要把从网络上抓取的图片批量上传到服务器,文件上传用的是Apache HttpClient 4.3,记录一下以便以后查阅!
代码如下:
/**
* Example how to use multipart/form encoded POST request.
*/
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample");
FileBody img = new FileBody(new File(args[0]));
StringBody filename = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("img", img)
.addPart("filename", filename)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
HttpClient的更多用法可参考官方文档:https://hc.apache.org/httpcomponents-client-4.3.x/examples.html
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇:PyQt写的图片浏览器
下一篇:Java判断图片格式的代码
最新资讯
热门推荐