標籤:android style blog http io ar os 使用 sp
最近在做 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 >= 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
public static HttpEntity makeMultipartEntity(List<NameValuePair> params, final Map<String, File> files) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//如果有SocketTimeoutException等情況,可修改這個枚舉 //builder.setCharset(Charset.forName("UTF-8"));//不要用這個,會導致服務端接收不到參數 if (params != null && params.size() > 0) { for (NameValuePair p : params) { builder.addTextBody(p.getName(), p.getValue(), ContentType.TEXT_PLAIN.withCharset("UTF-8")); } } if (files != null && files.size() > 0) { 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 != 1) { System.out.println("File path not given"); System.exit(1); } CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); 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表單提交方式的檔案上傳