HttpClient 4 3 6 使用MultipartEntityBuilder實現類似form表單提交方式的檔案上傳
阿新 • • 發佈:2018-11-12
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!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 框架,應該都可以使用。
不知道怎麼使用?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等情況,可修改這個列舉
|