HttpClient如何进行文件上传呢?

打印 上一主题 下一主题

主题 1608|帖子 1608|积分 4824

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
转自:
http://www.java265.com/JavaCourse/202204/2938.html
HttpClient是一个java语言编写的包,
我们使用HttpClient可以非常方便的发送Http请求
它使基于Http协议请求内容变得非常简单
HttpClient是Apache Jakarta Common下的子项目 它里面封装了很多使用http协议访问的工具,可用于高效访问http
 
下文笔者讲述基于HttpClient Utils工具类编写一个文件上传的示例分享,如下所示:
  1. HttpClient Utils进行表单进行文件上传的示例分享,如下所示
  2. 实现思路:
  3.     1.获取连接
  4.         2.声明一个HttpPost
  5.         3.创建上传体FileBody
  6.         4.定义一个HttpEntity传送文件
  7.         5.execute执行上传操作
  8.         6.获取返回信息
  9.         7.关闭连接
复制代码
  1. /**
  2.      * 上传文件
  3.      */   
  4.     public void upload() {   
  5.         CloseableHttpClient httpclient = HttpClients.createDefault();   
  6.         try {   
  7.             HttpPost httppost = new HttpPost("http://java265.com/uploadFile");   
  8.      
  9.             FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));   
  10.             StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);   
  11.      
  12.             HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();   
  13.      
  14.             httppost.setEntity(reqEntity);   
  15.      
  16.             System.out.println("executing request " + httppost.getRequestLine());   
  17.             CloseableHttpResponse response = httpclient.execute(httppost);   
  18.             try {   
  19.                 System.out.println("----------------------------------------");   
  20.                 System.out.println(response.getStatusLine());   
  21.                 HttpEntity resEntity = response.getEntity();   
  22.                 if (resEntity != null) {   
  23.                     System.out.println("Response content length: " + resEntity.getContentLength());   
  24.                 }   
  25.                 EntityUtils.consume(resEntity);   
  26.             } finally {   
  27.                 response.close();   
  28.             }   
  29.         } catch (ClientProtocolException e) {   
  30.             e.printStackTrace();   
  31.         } catch (IOException e) {   
  32.             e.printStackTrace();   
  33.         } finally {   
  34.             try {   
  35.                 httpclient.close();   
  36.             } catch (IOException e) {   
  37.                 e.printStackTrace();   
  38.             }   
  39.         }   
  40.     }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

羊蹓狼

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表