HttpClient使用MultipartEntityBuilder實現多檔案上傳
阿新 • • 發佈:2019-01-07
package com.jph.ufh.service; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.DefaultHttpClient; import android.os.Handler; /** * 採用HttpClient上傳檔案,支援多檔案上傳 * @author jph * Date:2014.10.09 */ public class UploadService { private static String url="http://10.219.57.16:8080/ServerForUpload/ServletForUpload"; // private static String url="http://10.110.6.58:8080/ServerForUpload/ServletForUpload"; public static final int UPLOAD_SUCCESS=0x123; public static final int UPLOAD_FAIL=0x124; private Handler handler; public UploadService(Handler handler) { // TODO Auto-generated constructor stub this.handler=handler; } /** * @param params 請求引數,包括請求的的方法引數method如:“upload”, * 請求上傳的檔案型別fileTypes如:“.jpg.png.docx” * @param files 要上傳的檔案集合 */ public void uploadFileToServer(final Map<String, String> params, final ArrayList<File>files) { // TODO Auto-generated method stub new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { if (uploadFiles(url,params,files)) { handler.sendEmptyMessage(UPLOAD_SUCCESS);//通知主執行緒資料傳送成功 }else { //將資料傳送給伺服器失敗 } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } /** * @param url servlet的地址 * @param params 要傳遞的引數 * @param files 要上傳的檔案 * @return true if upload success else false * @throws ClientProtocolException * @throws IOException */ private boolean uploadFiles(String url,Map<String, String>params,ArrayList<File>files) throws ClientProtocolException, IOException { HttpClient client=new DefaultHttpClient();// 開啟一個客戶端 HTTP 請求 HttpPost post = new HttpPost(url);//建立 HTTP POST 請求 MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(Charset.forName("uft-8"));//設定請求的編碼格式 builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//設定瀏覽器相容模式 int count=0; for (File file:files) { builder.addBinaryBody("file"+count, file); count++; } builder.addTextBody("method", params.get("method"));//設定請求引數 builder.addTextBody("fileTypes", params.get("fileTypes"));//設定請求引數 HttpEntity entity = builder.build();// 生成 HTTP POST 實體 post.setEntity(entity);//設定請求引數 HttpResponse response = client.execute(post);// 發起請求 並返回請求的響應 if (response.getStatusLine().getStatusCode()==200) { return true; } return false; } }