httpclient-4.0.1應用指南

HttpClient程序包是一個實現了HTTP協議的客戶端編程工具包,要想熟練的掌握它,必須熟悉HTTP協議。


一個最簡單的調用程序如下:

HttpClient client = new DefaultHttpClient();// 核心應用

HttpRequest request = new HttpGet("http://www.jd.com/");// HTTP請求

System.out.println(request.getRequestLine());// 打印請求信息

        // 打印結果:GET http://www.jd.com/ HTTP/1.1

try {

HttpResponse response = client.execute((HttpUriRequest) request);// 發送請求,返回響應

System.out.println(response.getStatusLine());// 打印響應信息

                // 打印結果:HTTP/1.1 200 OK

} catch (ClientProtocolException e) {

// 協議錯誤

e.printStackTrace();

} catch (IOException e) {

// 網絡異常

e.printStackTrace();

}


核心對象client的調用非常直觀,其execute方法傳入一個request對象,返回一個response對象。使用client發出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請求:


HttpUriRequest request = new HttpPost(strUrl);


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

request-line

request-line方式是指在請求行上通過URI直接提供參數。

(1) 

我們可以在生成request對象時提供帶參數的URI,如:

HttpUriRequest request = new HttpGet("http://localhost/index.html?param1=value1&param2=value2");

(2)

另外,HttpClient程序包爲我們提供了URIUtils工具類,可以通過它生成帶參數的URI,如:

String scheme = "http";// 協議

String host = "localhost";// 主機名

int port = 8080;// 可選的端口

String path = "index.html";// 資源的路徑

String query = "param1=value1&param2=value2";// 可選的查詢

String fragment = null;// 可選的片段

URI uri =URIUtils.createURI(scheme, host, port, path, query, fragment);

System.out.println(uri); //http://localhost:8080/index.html?param1=value1&param2=value2

(3) 

需要注意的是,如果參數中含有中文,需將參數進行URLEncoding處理,如:

String scheme = "http";// 協議

String host = "localhost";// 主機名

int port = 8080;// 可選的端口

String path = "index.html";// 資源的路徑

String query = "param1="+URLEncoder.encode("中國", "utf-8")+"&param2=value2";//可選的查詢

String fragment = null;// 可選的片段

URI uri =URIUtils.createURI(scheme, host, port, path, query, fragment);

System.out.println(uri); //http://localhost:8080/index.html?param1=%E4%B8%AD%E5%9B%BD&param2=value2

(4) 

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

String scheme = "http";// 協議

String host = "localhost";// 主機名

int port = 8080;// 可選的端口

String path = "index.html";// 資源的路徑

List<NameValuePair> params = new ArrayList<NameValuePair>();// 查詢字符串參數列表

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

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

String query = URLEncodedUtils.format(params, "UTF-8");// 可選的查詢

String fragment = null;// 可選的片段

URI uri =URIUtils.createURI(scheme, host, port, path, query, fragment);

System.out.println(uri); //http://localhost:8080/index.html?param1=%E4%B8%AD%E5%9B%BD&param2=value2


request-body

與request-line方式不同,request-body方式是在request-body中提供參數,此方式只能用於POST請求。在HttpClient程序包中有兩個類可以完成此項工作,它們分別是UrlEncodedFormEntity類與MultipartEntity類。這兩個類均實現了HttpEntity接口。

(1) 

使用最多的是UrlEncodedFormEntity類。通過該類創建的對象可以模擬傳統的HTML表單傳送POST請求中的參數。如下面的表單:

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

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

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

    <inupt type="submit" value="submit"/>

</form>  

我們可以用下面的代碼實現:

List<NameValuePair> formParams = new ArrayList<NameValuePair>();

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

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

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

 

HttpPost request = new HttpPost(“http://localhost/index.html”);

request.setEntity(entity);  

當然,如果想查看HTTP數據格式,可以通過HttpEntity對象的各種方法取得。如:

List<NameValuePair> formParams = new ArrayList<NameValuePair>();

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

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

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

 

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

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

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

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

上例的打印結果如下:

Content-Type: application/x-www-form-urlencoded; charset=UTF-8

39

UTF-8

param1=%E4%B8%AD%E5%9B%BD&param2=value2

(2) 

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

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

        enctype="multipart/form-data">

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

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

    <input type="file" name="param3"/>

    <inupt type="submit" value="submit"/>

</form>  

我們可以用下面的代碼實現:

MultipartEntity entity = new MultipartEntity();

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

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

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

 

HttpPost request = new HttpPost(“http://localhost/index.html”);

request.setEntity(entity);



HTTP響應

HttpClient程序包對於HTTP響應的處理較之HTTP請求來說是簡單多了,其過程同樣使用了HttpEntity接口。我們可以從HttpEntity對象中取出數據流(InputStream),該數據流就是服務器返回的響應數據。需要注意的是,HttpClient程序包不負責解析數據流中的

內容。如:

HttpUriRequest request = ...;

HttpResponse response = httpClient.execute(request);

 

HttpEntity entity = response.getEntity();// 從response中取出HttpEntity對象

 

// 查看entity的各種指標

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

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

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

 

InputStream stream = entity.getContent();// 取出服務器返回的數據流

 

// 以任意方式操作數據流stream

// 調用方式 略 












發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章