HttpClient4文件上传

httpclient上传文件实际上就是模拟一个http的表单提交请求。 
Java代码   收藏代码
  1. package test.httpclient4;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5.   
  6. import org.apache.http.HttpEntity;  
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.HttpStatus;  
  9. import org.apache.http.client.ClientProtocolException;  
  10. import org.apache.http.client.HttpClient;  
  11. import org.apache.http.client.methods.HttpPost;  
  12. import org.apache.http.entity.mime.MultipartEntity;  
  13. import org.apache.http.entity.mime.content.FileBody;  
  14. import org.apache.http.entity.mime.content.StringBody;  
  15. import org.apache.http.impl.client.DefaultHttpClient;  
  16. import org.apache.http.util.EntityUtils;  
  17.   
  18. public class SendFile {  
  19.   
  20.     public static void main(String[] args) throws ClientProtocolException,  
  21.             IOException {  
  22.         HttpClient httpclient = new DefaultHttpClient();  
  23.         //请求处理页面  
  24.         HttpPost httppost = new HttpPost(  
  25.                 "http://localhost:8080/webtools/upload.jsp");  
  26.         //创建待处理的文件  
  27.         FileBody file = new FileBody(new File("d:/22.rar"));  
  28.         //创建待处理的表单域内容文本  
  29.         StringBody descript = new StringBody("0431.la");  
  30.   
  31.         //对请求的表单域进行填充  
  32.         MultipartEntity reqEntity = new MultipartEntity();  
  33.         reqEntity.addPart("file", file);  
  34.         reqEntity.addPart("descript", descript);  
  35.         //设置请求  
  36.         httppost.setEntity(reqEntity);  
  37.         //执行  
  38.         HttpResponse response = httpclient.execute(httppost);  
  39.         //HttpEntity resEntity = response.getEntity();  
  40.         //System.out.println(response.getStatusLine());  
  41.         if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){  
  42.             HttpEntity entity = response.getEntity();  
  43.             //显示内容  
  44.             if (entity != null) {  
  45.                 System.out.println(EntityUtils.toString(entity));  
  46.             }  
  47.             if (entity != null) {  
  48.                 entity.consumeContent();  
  49.             }  
  50.         }  
  51.     }  
  52. }  

这里说明一下 需要一个额外的包,apache 的mime4j 的lib。 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值