HttpClient如何进行文件上传呢?
下文笔者讲述基于HttpClient Utils工具类编写一个文件上传的示例分享,如下所示:
HttpClient Utils进行表单进行文件上传的示例分享,如下所示
实现思路:
1.获取连接
2.声明一个HttpPost
3.创建上传体FileBody
4.定义一个HttpEntity传送文件
5.execute执行上传操作
6.获取返回信息
7.关闭连接
/**
* 上传文件
*/
public void upload() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://java265.com/uploadFile");
FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).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();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
参考资料:http://www.java265.com/JavaCourse/202204/2934.html
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


