學習腳步--- HttpClient4.0, multipartEntity (轉)

學習腳步--- HttpClient4.0html

Apache網絡協議網絡應用應用服務器HTML java

HttpClient程序包是一個實現了 HTTP 協議的客戶端編程工具包,要想熟練的掌握它,必須熟悉 HTTP協議。一個最簡單的調用以下:apache

Java代碼 複製代碼 收藏代碼編程

  1. import java.io.IOException;   服務器

  2. import org.apache.http.HttpResponse;   網絡

  3. import org.apache.http.client.ClientProtocolException;   app

  4. import org.apache.http.client.HttpClient;   ssh

  5. import org.apache.http.client.methods.HttpGet;   工具

  6. import org.apache.http.client.methods.HttpUriRequest;   學習

  7. import org.apache.http.impl.client.DefaultHttpClient;   

  8.   

  9. public class Test {   

  10.     public static void main(String[] args) {   

  11.   

  12.        // 核心應用類   

  13.        HttpClient httpClient = new DefaultHttpClient();   

  14.   

  15.         // HTTP請求   

  16.         HttpUriRequest request =   

  17.                 new HttpGet("http://localhost/index.html");   

  18.   

  19.         // 打印請求信息   

  20.         System.out.println(request.getRequestLine());   

  21.         try {   

  22.             // 發送請求,返回響應   

  23.             HttpResponse response = httpClient.execute(request);   

  24.   

  25.             // 打印響應信息   

  26.             System.out.println(response.getStatusLine());   

  27.         } catch (ClientProtocolException e) {   

  28.             // 協議錯誤   

  29.             e.printStackTrace();   

  30.         } catch (IOException e) {   

  31.             // 網絡異常   

  32.             e.printStackTrace();   

  33.         }   

  34.     }   

  35. }  

Java代碼 複製代碼 收藏代碼

  1. import java.io.IOException;  

  2. import org.apache.http.HttpResponse;  

  3. import org.apache.http.client.ClientProtocolException;  

  4. import org.apache.http.client.HttpClient;  

  5. import org.apache.http.client.methods.HttpGet;  

  6. import org.apache.http.client.methods.HttpUriRequest;  

  7. import org.apache.http.impl.client.DefaultHttpClient;  

  8.   

  9. public class Test {  

  10.     public static void main(String[] args) {  

  11.   

  12.        // 核心應用類  

  13.        HttpClient httpClient = new DefaultHttpClient();  

  14.   

  15.         // HTTP請求  

  16.         HttpUriRequest request =  

  17.                 new HttpGet("http://localhost/index.html");  

  18.   

  19.         // 打印請求信息  

  20.         System.out.println(request.getRequestLine());  

  21.         try {  

  22.             // 發送請求,返回響應  

  23.             HttpResponse response = httpClient.execute(request);  

  24.   

  25.             // 打印響應信息  

  26.             System.out.println(response.getStatusLine());  

  27.         } catch (ClientProtocolException e) {  

  28.             // 協議錯誤  

  29.             e.printStackTrace();  

  30.         } catch (IOException e) {  

  31.             // 網絡異常  

  32.             e.printStackTrace();  

  33.         }  

  34.     }  

  35. }  

 

若是HTTP服務器正常而且存在相應的服務,則上例會打印出兩行結果:

GET http://localhost/index.html HTTP/1.1
HTTP/1.1 200 OK

 核心對象httpClient的調用很是直觀,其execute方法傳入一個request對象,返回一個response對象。使用httpClient發出HTTP請求時,系統可能拋出兩種異常,分別是ClientProtocolException和IOException。第一種異常的發生一般是協議錯誤致使,如在構造HttpGet對象時傳入的協議不對(例如不當心將"http"寫成"htp"),或者服務器端返回的內容不符合HTTP協議要求等;第二種異常通常是因爲網絡緣由引發的異常,如HTTP服務器未啓動等。
從實際應用的角度看,HTTP協議由兩大部分組成:HTTP請求和HTTP響應。那麼HttpClient程序包是如何實現HTTP客戶端應用的呢?實現過程當中須要注意哪些問題呢?

HTTP請求

HTTP 1.1由如下幾種請求組成:GET, HEAD, POST, PUT, DELETE, TRACE and OPTIONS, 程序包中分別用HttpGet, HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, and HttpOptions 這幾個類建立請求。全部的這些類均實現了HttpUriRequest接口,故能夠做爲execute的執行參數使用。
全部請求中最經常使用的是GET與POST兩種請求,與建立GET請求的方法相同,能夠用以下方法建立一個POST請求:

Java代碼 複製代碼 收藏代碼

  1. HttpUriRequest request = new HttpPost(   

  2.         "http://localhost/index.html");  

Java代碼 複製代碼 收藏代碼

  1. HttpUriRequest request = new HttpPost(  

  2.         "http://localhost/index.html");  

 

HTTP請求格式 告訴咱們,有兩個位置或者說兩種方式能夠爲request提供參數:request-line方式與request-body方式。

request-line

request-line方式是指在請求行上經過URI直接提供參數。
(1)
咱們能夠在生成request對象時提供帶參數的URI,如:

Java代碼 複製代碼 收藏代碼

  1. HttpUriRequest request = new HttpGet(   

  2.         "http://localhost/index.html?param1=value1&param2=value2");  

Java代碼 複製代碼 收藏代碼

  1. HttpUriRequest request = new HttpGet(  

  2.         "http://localhost/index.html?param1=value1&param2=value2");  

 

(2)

另外,HttpClient程序包爲咱們提供了URIUtils工具類,能夠經過它生成帶參數的URI,如:

Java代碼 複製代碼 收藏代碼

  1. URI uri = URIUtils.createURI("http""localhost", -1"/index.html",   

  2.     "param1=value1&param2=value2"null);   

  3. HttpUriRequest request = new HttpGet(uri);   

  4. System.out.println(request.getURI());  

Java代碼 複製代碼 收藏代碼

  1. URI uri = URIUtils.createURI("http""localhost", -1"/index.html",  

  2.     "param1=value1&param2=value2"null);  

  3. HttpUriRequest request = new HttpGet(uri);  

  4. System.out.println(request.getURI());  

 

上例的打印結果以下:

http://localhost/index.html?param1=value1&param2=value2

 

(3)
須要注意的是,若是參數中含有中文,需將參數進行URLEncoding處理,如:

Java代碼 複製代碼 收藏代碼

  1. String param = "param1=" + URLEncoder.encode("中國""UTF-8") + "&param2=value2";   

  2. URI uri = URIUtils.createURI("http""localhost"8080,   

  3. "/sshsky/index.html", param, null);   

  4. System.out.println(uri);  

Java代碼 複製代碼 收藏代碼

  1. String param = "param1=" + URLEncoder.encode("中國""UTF-8") + "&param2=value2";  

  2. URI uri = URIUtils.createURI("http""localhost"8080,  

  3. "/sshsky/index.html", param, null);  

  4. System.out.println(uri);  

 

上例的打印結果以下:

http://localhost/index.html?param1=中國&param2=value2

 

(4)
對於參數的URLEncoding處理,HttpClient程序包爲咱們準備了另外一個工具類:URLEncodedUtils。經過它,咱們能夠直觀的(可是比較複雜)生成URI,如:

Java代碼 複製代碼 收藏代碼

  1. List params = new ArrayList();   

  2. params.add(new BasicNameValuePair("param1""中國"));   

  3. params.add(new BasicNameValuePair("param2""value2"));   

  4. String param = URLEncodedUtils.format(params, "UTF-8");   

  5. URI uri = URIUtils.createURI("http""localhost"8080,   

  6. "/sshsky/index.html", param, null);   

  7. System.out.println(uri);  

Java代碼 複製代碼 收藏代碼

  1. List params = new ArrayList();  

  2. params.add(new BasicNameValuePair("param1""中國"));  

  3. params.add(new BasicNameValuePair("param2""value2"));  

  4. String param = URLEncodedUtils.format(params, "UTF-8");  

  5. URI uri = URIUtils.createURI("http""localhost"8080,  

  6. "/sshsky/index.html", param, null);  

  7. System.out.println(uri);  

 

上例的打印結果以下:

http://localhost/index.html?param1=中國&param2=value2

 

request-body

與request-line方式不一樣,request-body方式是在request-body中提供參數,此方式只能用於POST請求。在HttpClient程序包中有兩個類能夠完成此項工做,它們分別是UrlEncodedFormEntity類與MultipartEntity類。這兩個類均實現了HttpEntity接口。
(1)
使用最多的是UrlEncodedFormEntity類。經過該類建立的對象能夠模擬傳統的HTML表單傳送POST請求中的參數。以下面的表單:

Html代碼 複製代碼 收藏代碼

  1. <</SPAN>form action="http://localhost/index.html" method="POST">  

  2.     <</SPAN>input type="text" name="param1" value="中國"/>  

  3.     <</SPAN>input type="text" name="param2" value="value2"/>  

  4.     <</SPAN>inupt type="submit" value="submit"/>  

  5. </</SPAN>form>  

Html代碼 複製代碼 收藏代碼

  1. <</SPAN>form action="http://localhost/index.html" method="POST">  

  2.     <</SPAN>input type="text" name="param1" value="中國"/>  

  3.     <</SPAN>input type="text" name="param2" value="value2"/>  

  4.     <</SPAN>inupt type="submit" value="submit"/>  

  5. </</SPAN>form>  

 

 

咱們能夠用下面的代碼實現:

Java代碼 複製代碼 收藏代碼

  1. List formParams = new ArrayList();   

  2. formParams.add(new BasicNameValuePair("param1""中國"));   

  3. formParams.add(new BasicNameValuePair("param2""value2"));          

  4. HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");   

  5.     

  6. HttpPost request = new HttpPost(「http://localhost/index.html」);   

  7. request.setEntity(entity);  

Java代碼 複製代碼 收藏代碼

  1. List formParams = new ArrayList();  

  2. formParams.add(new BasicNameValuePair("param1""中國"));  

  3. formParams.add(new BasicNameValuePair("param2""value2"));         

  4. HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");  

  5.    

  6. HttpPost request = new HttpPost(「http://localhost/index.html」);  

  7. request.setEntity(entity);  

 

固然,若是想查看HTTP數據格式,能夠經過HttpEntity對象的各類方法取得。如:

Java代碼 複製代碼 收藏代碼

  1. List formParams = new ArrayList();   

  2. formParams.add(new BasicNameValuePair("param1""中國"));   

  3. formParams.add(new BasicNameValuePair("param2""value2"));          

  4. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");   

  5.     

  6. System.out.println(entity.getContentType());   

  7. System.out.println(entity.getContentLength());   

  8. System.out.println(EntityUtils.getContentCharSet(entity));   

  9. System.out.println(EntityUtils.toString(entity));  

Java代碼 複製代碼 收藏代碼

  1. List formParams = new ArrayList();  

  2. formParams.add(new BasicNameValuePair("param1""中國"));  

  3. formParams.add(new BasicNameValuePair("param2""value2"));         

  4. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");  

  5.    

  6. System.out.println(entity.getContentType());  

  7. System.out.println(entity.getContentLength());  

  8. System.out.println(EntityUtils.getContentCharSet(entity));  

  9. System.out.println(EntityUtils.toString(entity));  

 

上例的打印結果以下:

Content-Type: application/x-www-form-urlencoded; charset=UTF-8
39
UTF-8
param1=中國&param2=value2

 

(2)
除了傳統的application/x-www-form-urlencoded表單,咱們另外一個常常用到的是上傳文件用的表單,這種表單的類型爲multipart/form-data。在HttpClient程序擴展包(HttpMime)中專門有一個類與之對應,那就是MultipartEntity類。此類一樣實現了HttpEntity接口。以下面的表單:

Html代碼 複製代碼 收藏代碼

  1. <</SPAN>form action="http://localhost/index.html" method="POST"  

  2.         enctype="multipart/form-data">  

  3.     <</SPAN>input type="text" name="param1" value="中國"/>  

  4.     <</SPAN>input type="text" name="param2" value="value2"/>  

  5.     <</SPAN>input type="file" name="param3"/>  

  6.     <</SPAN>inupt type="submit" value="submit"/>  

  7. </</SPAN>form>  

Html代碼 複製代碼 收藏代碼

  1. <</SPAN>form action="http://localhost/index.html" method="POST"  

  2.         enctype="multipart/form-data">  

  3.     <</SPAN>input type="text" name="param1" value="中國"/>  

  4.     <</SPAN>input type="text" name="param2" value="value2"/>  

  5.     <</SPAN>input type="file" name="param3"/>  

  6.     <</SPAN>inupt type="submit" value="submit"/>  

  7. </</SPAN>form>  

  

 

咱們能夠用下面的代碼實現:

Java代碼 複製代碼 收藏代碼

  1. MultipartEntity entity = new MultipartEntity();   

  2. entity.addPart("param1"new StringBody("中國", Charset.forName("UTF-8")));   

  3. entity.addPart("param2"new StringBody("value2", Charset.forName("UTF-8")));   

  4. entity.addPart("param3"new FileBody(new File("C:\\1.txt")));   

  5.     

  6. HttpPost request = new HttpPost(「http://localhost/index.html」);   

  7. request.setEntity(entity);  

Java代碼 複製代碼 收藏代碼

  1. MultipartEntity entity = new MultipartEntity();  

  2. entity.addPart("param1"new StringBody("中國", Charset.forName("UTF-8")));  

  3. entity.addPart("param2"new StringBody("value2", Charset.forName("UTF-8")));  

  4. entity.addPart("param3"new FileBody(new File("C:\\1.txt")));  

  5.    

  6. HttpPost request = new HttpPost(「http://localhost/index.html」);  

  7. request.setEntity(entity);  

 

HTTP響應

HttpClient程序包對於HTTP響應的處理較之HTTP請求來講是簡單多了,其過程一樣使用了HttpEntity接口。咱們能夠從HttpEntity對象中取出數據流(InputStream),該數據流就是服務器返回的響應數據。須要注意的是,HttpClient程序包不負責解析數據流中的內容。如:

Java代碼 複製代碼 收藏代碼

  1. HttpUriRequest request = ...;   

  2. HttpResponse response = httpClient.execute(request);   

  3.     

  4. // 從response中取出HttpEntity對象   

  5. HttpEntity entity = response.getEntity();   

  6.     

  7. // 查看entity的各類指標   

  8. System.out.println(entity.getContentType());   

  9. System.out.println(entity.getContentLength());   

  10. System.out.println(EntityUtils.getContentCharSet(entity));   

  11.     

  12. // 取出服務器返回的數據流   

  13. InputStream stream = entity.getContent();   

  14.     

  15. // 以任意方式操做數據流stream   

  16. // 調用方式 略  

Java代碼 複製代碼 收藏代碼

  1. HttpUriRequest request = ...;  

  2. HttpResponse response = httpClient.execute(request);  

  3.    

  4. // 從response中取出HttpEntity對象  

  5. HttpEntity entity = response.getEntity();  

  6.    

  7. // 查看entity的各類指標  

  8. System.out.println(entity.getContentType());  

  9. System.out.println(entity.getContentLength());  

  10. System.out.println(EntityUtils.getContentCharSet(entity));  

  11.    

  12. // 取出服務器返回的數據流  

  13. InputStream stream = entity.getContent();  

  14.    

  15. // 以任意方式操做數據流stream  

  16. // 調用方式 略  

 

附註:

本文說明的是HttpClient 4.0.1 ,該程序包(包括依賴的程序包)由如下幾個JAR包組成: commons-logging-1.1.1.jarcommons-codec-1.4.jarhttpcore-4.0.1.jarhttpclient-4.0.1.jarapache-mime4j-0.6.jarhttpmime-4.0.1.jar

相關文章
相關標籤/搜索