ANDROID使用MULTIPARTENTITYBUILDER实现类似FORM表单提交方式的文件上传
最近在做 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表单提交方式的文件上传的更多相关文章
- Java后台使用httpclient入门HttpPost请求(form表单提交,File文件上传和传输Json数据)
一.HttpClient 简介 HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 ...
- js_ajax模拟form表单提交_多文件上传_支持单个删除
需求场景: 用一个input type="file"按钮上传多张图片,可多次上传,可单独删除,最后使用ajax模拟form表单提交功能提交到指定方法中: 问题:由于只有一个file ...
- 使用ajax提交form表单,包括ajax文件上传【转载】
[使用ajax提交form表单,包括ajax文件上传] 前言 转载:作者:https://www.cnblogs.com/zhuxiaojie/p/4783939.html 使用ajax请求数据,很多 ...
- 使用ajax提交form表单,包括ajax文件上传 转http://www.cnblogs.com/zhuxiaojie/p/4783939.html
使用ajax提交form表单,包括ajax文件上传 前言 使用ajax请求数据,很多人都会,比如说: $.post(path,{data:data},function(data){ ... },&qu ...
- Yii2表单提交(带文件上传)
今天写一个php的表单提交接口,除了基本的字符串数据,还带文件上传,不用说前端form标签内应该有这些属性 <form enctype="multipart/form-data&quo ...
- 使用ajax提交form表单,包括ajax文件上传
前言 使用ajax请求数据,很多人都会,比如说: $.post(path,{data:data},function(data){ ... },"json"); 又或者是这样的aja ...
- django项目中form表单和ajax的文件上传功能。
form表单文件上传 路由 # from表单上传 path('formupload/',apply.formupload,name='formupload/'), 方法 # form表单文件上传 de ...
- 使用bean接收ajax表单提交数据包含文件上传
这几天写带图片上传的表单提交,一个配置小程序活动弹出框样式的功能,记录一下一些需要注意的地方 首先是 前端 JSP 文件的表单 <form class="search-wrapper& ...
- 用div漂浮快实现与表单无关的多文件上传功能。
我项目有这个需求,多文件上传,而且要及时显示到表单上,这样的话就不能与表单相关. 由于我对前端不熟,我就实现了这么一个功能,通过button触发一个div漂浮块,然后多文件上传,之后通过js把文件名显 ...
随机推荐
- BZOJ1689: [Usaco2005 Open] Muddy roads
1689: [Usaco2005 Open] Muddy roads Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 147 Solved: 107[Su ...
- 【转】解决java.lang.IllegalStateException: The content of the adapter has changed but ListView...的问题
原文网址:http://blog.csdn.net/ueryueryuery/article/details/20607845 我写了一个Dialog,Dialog中有一个ListView,想要点Li ...
- day49
几天没写了 这几天比较麻木呢 各种课程的再看 想买一直不舍得money 今天下定决心买了 这样我也静下心好好备战把 一天背的东西好多 政治和作文也是背了就忘记 尽力把 今天的买的课很悬乎 就不在这说了 ...
- 第19讲- UI组件之_Button、checkbox、radio
第19讲 UI组件之_Button.checkbox.radio 四.按钮Button Button继承自TextView,间接继承自View.当用户对按钮进行操作的时候,触发相应事件,如点击,触摸. ...
- java 图片 批量 压缩 +所有压缩
/* oldsrc : 原图片地址目录 如 'd:/' newsrc : 压缩后图片地址目录 如 'e:/' widthdist,heightdist : 压缩后的宽和高 ...
- windows下绑定线程(进程)到指定的CPU核心
一个程序指定到单独一个CPU上运行会比不指定CPU运行时快.这中间主要有两个原因:1)CPU切换时损耗的性能.2)Intel的自动降频技术和windows的机制冲突:windows有一个功能是平衡负载 ...
- <经验杂谈>C#/.Net字符串操作方法小结
字符串操作是C#中最基本的.最常见的.也是用的最多的,以下我总结 了几种常见的方法 1.把字符串按照分隔符转换成 List /// <summary> /// 把字符串按照分隔符转换成 L ...
- 从反编译的角度去观察C#6.0
1. 自动属性初始化 (Initializers for auto-properties) 1.1 C#6.0 之前的写法 public class FirstExperience { private ...
- Java这个名字怎么来
Java语言的历程丰富多彩,被现在众多程序员和企业广泛使用,不用质疑这是Java的领先技术的结果. Java是Sun公司开发的一种编程语言,Sun公司最初的方向是让Java来开发一些电器装置程序, ...
- redis基础操作
/** * redis的Java客户端Jedis测试验证 * * @author */ public class Test { /** * 非切片客户端链接 */ private Jedis jedi ...