1. 程式人生 > >HttpClient傳送方實現上傳多個檔案

HttpClient傳送方實現上傳多個檔案

public static void upload(String url, List<String> filepaths,HashMap<String, String> mapParams) {  
        HttpClient client = new DefaultHttpClient();  
        HttpPost httpPost = new HttpPost(url);  
        client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);  
        client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "utf-8"
); try { MultipartEntity entity = new MultipartEntity();//多個表單物件 for(String filepath:filepaths){ ContentBody fileBody = new FileBody(new File(filepath)); //表單檔案域 entity.addPart("file", fileBody); } entity.addPart("userName"
, new StringBody(mapParams.get("userName"))); // 字元引數部分 httpPost.setEntity(entity); HttpResponse response = client.execute(httpPost);//執行post操作,並返回response if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ String jsonData = EntityUtils.toString(response.getEntity(), "UTF-8"
); System.out.println("response result="+jsonData); }else{ System.out.println("no response"); } } catch (Exception e) { e.printStackTrace(); } }