html中的form 表單有兩種:除了傳統的application/x-www-form-urlencoded表單,咱們另外一個常常用到的是上傳文件用的表單,這種表單的類型爲multipart/form-data。 後者主要是用來上傳文件所用,因此通常狀況下,在使用webservice 時,使用UrlEncodedFormEntity 比較多,UrlEncodedFormEntity 能夠模擬傳統的HTML表單傳送POST請求中的參數,html
如:html表單以下:java
<form action=」http://localhost/index.html」 method=」POST」>
<input type=」text」 name=」param1″ value=」李三」/>
<input type=」text」 name=」param2″ value=」男」/>
<inupt type=」submit」 value=」submit」/>
</form>web
代碼以下:apache
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair(「param1″, 「李三」));
formParams.add(new BasicNameValuePair(「param2″, 「男」));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, 「UTF-8″);app
MultipartEntity 則與form類型爲multipart/form-data 對應,如 html from 以下:ui
<form action=」http://localhost/index.html」 method=」POST」
enctype=」multipart/form-data」>
<input type=」text」 name=」param1″ value=」李三」/>
<input type=」text」 name=」param2″ value=」男」/>
<input type=」file」 name=」param3″/>
<inupt type=」submit」 value=」submit」/>
</form>url
代碼以下:code
MultipartEntity entity = new MultipartEntity();
entity.addPart(「param1″, new StringBody(「李三」, Charset.forName(「UTF-8″)));
entity.addPart(「param2″, new StringBody(「男」, Charset.forName(「UTF-8″)));
entity.addPart(「param3″, new FileBody(new File(「C:\\pic.gif」)));orm
/* org.apache.http.entity.mime.content.FileBody.FileBody org.apache.http.client.methods.HttpPost.HttpPost org.apache.http.entity.mime.MultipartEntityBuilder org.apache.http.client.methods.CloseableHttpResponse org.apache.http.HttpEntity */ CloseableHttpResponse response = null; HttpEntity entity = null; String result = null; try { FileBody bin = new FileBody(uploadImgRequest.getFile()); HttpPost httpPost = new HttpPost(uploadImgRequest.getUrl()); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("buffer", bin) .addTextBody("access_token", uploadImgRequest.getAccess_token()) .build(); httpPost.setEntity(reqEntity); response = httpClient.execute(httpPost); entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpPost.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode+",result:"+result); } }