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把文件名显 ...
随机推荐
- BZOJ2023: [Usaco2005 Nov]Ant Counting 数蚂蚁
2023: [Usaco2005 Nov]Ant Counting 数蚂蚁 Time Limit: 4 Sec Memory Limit: 64 MBSubmit: 56 Solved: 16[S ...
- 湖南生第八届大学生程序设计大赛原题 C-Updating a Dictionary(UVA12504 - Updating a Dictionary)
UVA12504 - Updating a Dictionary 给出两个字符串,以相同的格式表示原字典和更新后的字典.要求找出新字典和旧字典的不同,以规定的格式输出. 算法操作: (1)处理旧字典, ...
- LeetCode 191. Number of 1 Bits Question
题意:给你一个整数,计算该整数的二进制形式里有多少个“1”.比如6(110),就有2个“1”. 一开始我就把数字n不断右移,然后判定最右位是否为1,是就cnt++,否则就继续右移直到n为0. 可是题目 ...
- 【Eclipse DDMS】 Can't bind to local 8600 for debugger
问题原因: 电脑上同时安装了Eclipse 和Android Studio两个ide. 关键是使用eclipse adb连接真机时候,android studio也处于运行状态,后者默认也是要连接ad ...
- hdu 1695 GCD(欧拉函数+容斥)
Problem Description Given 5 integers: a, b, c, d, k, you're to find x in a...b, y in c...d that GCD( ...
- opencv 实现进度控制
进度控制: #include <opencv\cv.h> #include <opencv\highgui.h> #include <opencv\cxcore.h> ...
- Activity中的startActivityResult,setResult,finish,onActivityResult的关系
一:首先图示: 二:代码: 1:方法selectName public void selectName(View view){ Intent intent = new Intent(this,Name ...
- 使用apktool解包和打包apk
使用apktool解包和打包apk 下载apktool工具 解包 apktool d xxx.apk -f 植入代码 使用apktool解包要植入代码的apk(下面称为A), 使用apktool解包包 ...
- 先装Net Framework 后 装 IIS的处理办法
先装IIS话,后面装Net Framework时候会自动注册 处理aspx和ashx等的处理扩展程序 先装Net Framework 后 装 IIS.扩展程序注册在命令:aspnet_regiis - ...
- WndPric的使用方法
protected override void WndProc(ref Message m) { const int WM_SYSCOMMAND = 0x0112; const int SC_CLOS ...