HttpClient 4 3 6 使用MultipartEntityBuilder实现类似form表单提交方式的文件上传

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

    

<dependency>            <groupId>org.apache.httpcomponents</groupId>            <artifactId>httpclient</artifactId>            <version>4.5</version>        </dependency>        <dependency>            <groupId>org.apache.httpcomponents</groupId>            <artifactId>httpmime</artifactId>            <version>4.5</version>        </dependency>


最近在做 Android 端文件上传,要求采用 form 表单的方式提交,项目使用的 afinal 框架有文件上传功能,但是始终无法与php写的服务端对接上,无法上传成功。读源码发现:afinal 使用了某大神写的 MultipartEntity.java 生成 form 表单内容,然而生成的内容格式不够标准,而且还存在诸多问题,如:首先将所有文件读入到内存,再生成字节流写入到 socket。那么问题来了:如果是几百MB的文件怎么办?

      几番搜索,受到 这篇文章(已被我转载,但是示例代码已过期的启发,我辗转找到了 Apache 源码 httpcomponents-client-4.3.6-src.zip,在一个示例里面发现了一个重要的组件 MultipartEntityBuilder, 可以生成 form 表单格式的 HttpEntity, 有了 HttpEntity, 无论你是什么 http 框架,应该都可以使用。


扫描二维码关注公众号,回复: 4039310 查看本文章

不知道怎么使用?like this:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
HttpPost httppost =  new  HttpPost(url);
...
final  HttpEntity entity = makeMultipartEntity(params, files);
httppost.addHeader(entity.getContentType());
//httppost.addHeader(entity.getContentEncoding());    //null
httppost.setEntity(entity);
HttpResponse response = getHttpClient().execute(httppost);
...
 
private  static  HttpClient mClient;
private  static  HttpClient getHttpClient() {
     if (mClient ==  null ) {
         //if(Build.VERSION.SDK_INT >= 9);    //将不走本类的Case,基于HttpURLConnection
         if (Build.VERSION.SDK_INT >=  8 ) {
             mClient = AndroidHttpClient.newInstance(getUserAgent());
         } else  {
             mClient =  new  DefaultHttpClient();
         }
     }
     return  mClient;
}

MultipartEntityBuilder 用法整理如下:

需要用到 httpcomponents-client-4.3.6-bin.zip 中的 httpmime-4.3.6.jar 和 httpcore-4.3.3.jar

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public  static  HttpEntity makeMultipartEntity(List<NameValuePair> params,  final  Map<String, File> files) {
     MultipartEntityBuilder builder = MultipartEntityBuilder.create();
     builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);  //如果有SocketTimeoutException等情况,可修改这个枚举

猜你喜欢

转载自blog.csdn.net/hgffhh/article/details/83935027