1. 程式人生 > >HttpClient 4.0的使用詳解

HttpClient 4.0的使用詳解

HttpClient程式包是一個實現了 HTTP協議的客戶端程式設計工具包,要想熟練的掌握它,必須熟悉 HTTP協議。對於HTTP協議來說,無非就是使用者請求資料,伺服器端響應使用者請求,並將內容結果返回給使用者。HTTP1.1由以下幾種請求組成:GET,HEAD, POST, PUT, DELETE, TRACE ,OPTIONS,因此對應到HttpClient程式包中分別用HttpGet,HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, HttpOptions 這幾個類來建立請求。所有的這些類均實現了HttpUriRequest介面,故可以作為execute的執行引數使用。

HTTP請求

當然在所有請求中最常用的還是GET與POST兩種請求,建立請求的方式如下: 

HttpUriRequest request = newHttpPost("http://localhost/index.html");

HTTP請求格式告訴我們,有兩種方式可以為request提供引數:request-line方式與request-body方式。

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

(1)可以在生成request物件時提供帶引數的URI,如:

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

(2)HttpClient程式包還提供了URIUtils工具類,可以通過它生成帶引數的URI,如: 

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

   "param1=value1&param2=value2", null);

HttpUriRequest request = newHttpGet(uri);

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

上例的例項結果如下:

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

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

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

URI uri =URIUtils.createURI("http", "localhost", 8080,"/sshsky/index.html",param, null);

System.out.println(uri);

 上例的例項結果如下:

  http://localhost/index.html?param1=%E4%B8%AD%E5%9B%BD&param2=value2

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

 List params = newArrayList();

params.add(newBasicNameValuePair("param1", "中國"));

params.add(newBasicNameValuePair("param2", "value2"));

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

URI uri =URIUtils.createURI("http", "localhost", 8080,"/sshsky/index.html",param, null);

System.out.println(uri);

 上例的例項結果如下:

Ø  request-body方式是指在請求的request-body中提供引數

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

(1)UrlEncodedFormEntity類,故名思意該類主要用於form表單提交。通過該類建立的物件可以模擬傳統的HTML表單傳送POST請求中的引數。如下面的表單:

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

    <inputtype="text" name="param1" value="中國"/>

    <inputtype="text" name="param2" value="value2"/>

    <inupttype="submit" value="submit"/>

</form>

即可以通過下面的程式碼實現:

List formParams = newArrayList();

formParams.add(newBasicNameValuePair("param1", "中國"));

formParams.add(newBasicNameValuePair("param2", "value2"));

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

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

request.setEntity(entity);

 當然,如果想檢視HTTP資料格式,可以通過HttpEntity物件的各種方法取得。如:

List formParams = newArrayList();

formParams.add(newBasicNameValuePair("param1", "中國"));

formParams.add(newBasicNameValuePair("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介面。如下面的表單:

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

       enctype="multipart/form-data">

    <inputtype="text" name="param1" value="中國"/>

    <inputtype="text" name="param2" value="value2"/>

    <inputtype="file" name="param3"/>

    <inupttype="submit" value="submit"/>

</form>

可以用下面的程式碼實現:

MultipartEntity entity = newMultipartEntity();

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 = newHttpPost(“http://localhost/index.html”);

request.setEntity(entity);

HTTP響應 

HttpClient 程式包對於HTTP響應的處理較請求來說簡單多了,其過程同樣使用了HttpEntity介面。我們可以從HttpEntity物件中取出資料流(InputStream),該資料流就是伺服器返回的響應資料。需要注意的是,HttpClient程式包不負責 解析資料流中的內容。如:

HttpUriRequest request = ...;

HttpResponse response =httpClient.execute(request);

// 從response中取出HttpEntity物件

HttpEntity entity =response.getEntity();

// 檢視entity的各種指標

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

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

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

// 取出伺服器返回的資料流

InputStream stream =entity.getContent();

或者採用如下的介面方式httpClient.execute(request,new ResponseHandler<T> response)進行呼叫,它的返回值直接對應的即為使用者自己想獲取的資料的型別及值。

具體例項解析,通過下述方法,即可獲取到指定url的頁面內容。

public static String executeStringByGet(String url, final Charset charset) {

        String result = "";

        HttpClient client = new DefaultHttpClient();

        HttpGet get = new HttpGet(url);

       

        try {

            result = client.execute(get, new ResponseHandler<String>() {

                @Override

                public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {

                    HttpEntity entity = response.getEntity();

                    if(entity != null) {

                        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                            return new String(EntityUtils.toByteArray(entity), charset.getValue());

                        }

                    }

                    return "";

                }

            });

        } catch (Exception e) {

            e.printStackTrace();

        }

 

        return result;

    }

HttpClient介面的詳細使用:

package com.wow.common.test;

 

import java.io.IOException;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

 

import org.apache.http.Header;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.HttpStatus;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

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

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

import org.apache.http.util.EntityUtils;

 

/**

 * 類HttpClientTest.java的實現描述:TODO 類實現描述

 * @author zheng.zhaoz 2012-2-9 下午07:33:18

 */

public class HttpClientTest {

 

    public static void main(String[] args) {

        HttpClient httpClient = new DefaultHttpClient();

        //建立一個httpGet方法

        HttpGet httpGet = new HttpGet("http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113252.html");

       

        //設定httpGet的引數資訊

        httpGet.setHeader("Accept", "Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

        httpGet.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");

        httpGet.setHeader("Accept-Encoding", "gzip, deflate");

        httpGet.setHeader("Accept-Language", "zh-cn,zh;q=0.5");

        httpGet.setHeader("Connection", "keep-alive");

        httpGet.setHeader("Cookie", "__utma=226521935.73826752.1323672782.1325068020.1328770420.6;");

        httpGet.setHeader("Host", "www.cnblogs.com");

        httpGet.setHeader("refer", "http://www.baidu.com/s?tn=monline_5_dg&bs=httpclient4+MultiThreadedHttpConnectionManager");

        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");

        System.out.println("Accept-Charset: " + httpGet.getFirstHeader("Accept-Charset"));

        System.out.println("Execute request: " + httpGet.getURI());

       

        HttpResponse response = null;

        try {

            response = httpClient.execute(httpGet);

        } catch (ClientProtocolException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

       

        //輸出響應的所有頭資訊

        if(response != null) {

            Header headers[] = response.getAllHeaders();

            int i = 0;

            while (i < headers.length) {

                System.out.println(headers[i].getName() + ":  " + headers[i].getValue());

                i++;

            }

            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                try {

                    HttpEntity entity = response.getEntity();

                    // 將原始碼流儲存在一個byte陣列當中,因為可能需要兩次用到該流

                    byte[] bytes = EntityUtils.toByteArray(entity);

                    String charSet = "";

                    // 如果頭部Content-Type中包含了編碼資訊,那麼我們可以直接在此處獲取

                    charSet = EntityUtils.getContentCharSet(entity);

                    System.out.println("In header: " + charSet);

                    // 如果頭部中沒有,需要 檢視頁面原始碼,這個方法雖然不能說完全正確,因為有些粗糙的網頁編碼者沒有在頁面中寫頭部編碼資訊

                    if (charSet == "") {

                        String regEx="(?=<meta).*?(?<=charset=[\\'|\\\"]?)([[a-z]|[A-Z]|[0-9]|-]*)";

                        Pattern p=Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);

                        Matcher m=p.matcher(new String(bytes));  // 預設編碼轉成字串,因為我們的匹配中無中文,所以串中可能的亂碼對我們沒有影響

                        boolean result = m.find();

                        if (m.groupCount() == 1) {

                            charSet = m.group(1);

                        } else {

                            charSet = "";

                        }

                    }

                    System.out.println("Last get: " + charSet);

                    // 可以將原byte陣列按照正常編碼專成字串輸出(如果找到了編碼的話)

                    System.out.println("Encoding string is: " + new String(bytes, charSet));

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

        //關閉聯接

        httpClient.getConnectionManager().shutdown();   

    }

}