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

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

不知道怎么使用?like this:

HttpPost httppost = new HttpPost(url);
...
httppost.setEntity(makeMultipartEntity(params, files));
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 >= ) {
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

public static HttpEntity makeMultipartEntity(List<NameValuePair> params, final Map<String, File> files) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.STRICT); //如果有SocketTimeoutException等情况,可修改这个枚举
//builder.setCharset(Charset.forName("UTF-8")); //不要用这个,会导致服务端接收不到参数
if (params != null && params.size() > ) {
for (NameValuePair p : params) {
builder.addTextBody(p.getName(), p.getValue(), ContentType.TEXT_PLAIN.withCharset("UTF-8"));
}
}
if (files != null && files.size() > ) {
Set<Entry<String, File>> entries = files.entrySet();
for (Entry<String, File> entry : entries) {
builder.addPart(entry.getKey(), new FileBody(entry.getValue()));
}
}
return builder.build();
}

另附上 Apache 示例,可在 httpcomponents-client-4.3.6-bin.zip 中找到。

/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.entity.mime; import java.io.File; import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; /**
* Example how to use multipart/form encoded POST request.
*/
public class ClientMultipartFormPost { public static void main(String[] args) throws Exception {
if (args.length != ) {
System.out.println("File path not given");
System.exit();
}
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[]));
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();
}
} finally {
httpclient.close();
}
} }

ANDROID使用MULTIPARTENTITYBUILDER实现类似FORM表单提交方式的文件上传的更多相关文章

  1. Java后台使用httpclient入门HttpPost请求(form表单提交,File文件上传和传输Json数据)

    一.HttpClient 简介 HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 ...

  2. js_ajax模拟form表单提交_多文件上传_支持单个删除

    需求场景: 用一个input type="file"按钮上传多张图片,可多次上传,可单独删除,最后使用ajax模拟form表单提交功能提交到指定方法中: 问题:由于只有一个file ...

  3. 使用ajax提交form表单,包括ajax文件上传【转载】

    [使用ajax提交form表单,包括ajax文件上传] 前言 转载:作者:https://www.cnblogs.com/zhuxiaojie/p/4783939.html 使用ajax请求数据,很多 ...

  4. 使用ajax提交form表单,包括ajax文件上传 转http://www.cnblogs.com/zhuxiaojie/p/4783939.html

    使用ajax提交form表单,包括ajax文件上传 前言 使用ajax请求数据,很多人都会,比如说: $.post(path,{data:data},function(data){ ... },&qu ...

  5. Yii2表单提交(带文件上传)

    今天写一个php的表单提交接口,除了基本的字符串数据,还带文件上传,不用说前端form标签内应该有这些属性 <form enctype="multipart/form-data&quo ...

  6. 使用ajax提交form表单,包括ajax文件上传

    前言 使用ajax请求数据,很多人都会,比如说: $.post(path,{data:data},function(data){ ... },"json"); 又或者是这样的aja ...

  7. django项目中form表单和ajax的文件上传功能。

    form表单文件上传 路由 # from表单上传 path('formupload/',apply.formupload,name='formupload/'), 方法 # form表单文件上传 de ...

  8. 使用bean接收ajax表单提交数据包含文件上传

    这几天写带图片上传的表单提交,一个配置小程序活动弹出框样式的功能,记录一下一些需要注意的地方 首先是 前端 JSP 文件的表单 <form class="search-wrapper& ...

  9. 用div漂浮快实现与表单无关的多文件上传功能。

    我项目有这个需求,多文件上传,而且要及时显示到表单上,这样的话就不能与表单相关. 由于我对前端不熟,我就实现了这么一个功能,通过button触发一个div漂浮块,然后多文件上传,之后通过js把文件名显 ...

随机推荐

  1. logstash tomcat catalina.out zabbix 插件不会引起崩溃

    input { file { type => "zj_api" path => ["/data01/applog_backup/zjzc_log/zj-api ...

  2. hdu5014:number sequence对称思想

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=5014 题目大意:给定数组 a[]={0,1,2......n} 求一个数组b[] 元素也为0.... ...

  3. WPF - 为什么不能往Library的工程中添加WPF window

    项目中添加一个Library 工程,但是却无法加入WPF window, WPF customize control. 调查了一下,发现这一切都由于Library工程中没有:ProjectTypeGu ...

  4. hdu 5313 Bipartite Graph(dfs染色 或者 并查集)

    Problem Description Soda has a bipartite graph with n vertices and m undirected edges. Now he wants ...

  5. JPA字段映射(uuid,日期,枚举,@Lob)

    转:http://www.cnblogs.com/tazi/archive/2012/01/04/2311588.html 主键: JPA主键的生成策略不像Hibernate那么丰富. @Id @Ge ...

  6. android 4.0之前版本号出现JSONException异常

    今天在调试解析server传过来的JSON数据时,在2.3.7的手机上报了以下这样一个异常. 08-07 22:00:29.597: W/System.err(7610): org.json.JSON ...

  7. 杭电 HDU ACM Milk

    Milk Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submi ...

  8. BUG出现的地方真的令我这个测试新人想象不到

    今天上班,仍然在等待下一阶段项目的研发完成. 没有正式测试任务的我,作为新手肯定要趁着这个时间好好学习了,偶尔再拿出公司已经上线发布的APP来到处看看. 就在这偶尔的情况下让我发现了一个在正式测试时根 ...

  9. WebSphere之wasprofile.sh使用

    概要文件(profile) 6.0版本以后才有profile,目的是将用户数据和was本身的文件分开,这样可以定义多个profile,每个profile相当于一个用户,相当于提供了多用户的支持. pr ...

  10. UITableView的简单总结与回顾

    今天突发奇想的想对UItableView做一下汇总,感觉在编程中这个控件可以千变万化也是用的最多的一个了,下面就为大家简单总结下这个控件,也许还有不足,不过还是请各位不吝赐教了哈,那么我就开始了,我会 ...