HttpClient詳解(二)—請求詳解

上篇主要介紹了HttpClient的一些簡介及其基本的請求執行過程,下面繼續對請求工程中涉及到的類及方法進行學習。

Demo

先來看下基本的請求響應的一個過程(Get類型爲例,獲取天氣預報的一個http接口),以此我們來進行研究:


    import java.io.IOException;  
    import org.apache.http.HttpResponse;  
    import org.apache.http.client.ClientProtocolException;  
    import org.apache.http.client.HttpClient;  
    import org.apache.http.client.methods.HttpGet;  
    import org.apache.http.client.methods.HttpUriRequest;  
    import org.apache.http.impl.client.DefaultHttpClient;  
      
    public class Test {  
        public static void main(String[] args) {  
      
           // 核心應用類  
           HttpClient httpClient = new DefaultHttpClient();  
      
            // HTTP請求  
            HttpGet request = new HttpGet("http://weather.51wnl.com/weatherinfo/GetMoreWeather?cityCode=101010100&weatherType=0");  
      
            // 打印請求信息  
            System.out.println(request.getRequestLine());  
            try {  
                // 發送請求,返回響應  
                HttpResponse response = httpClient.execute(request);  
      
                // 打印響應信息  
                System.out.println(response.getStatusLine());  
            } catch (ClientProtocolException e) {  
                // 協議錯誤  
                e.printStackTrace();  
            } catch (IOException e) {  
                // 網絡異常  
                e.printStackTrace();  
            }  
        }  
    }  


請求

  HttpClient支持所有定義在HTTP/1.1版本中的HTTP方法:GET,HEAD,POST,PUT,DELETE,TRACE和OPTIONS。對於每個方法類型都有一個特殊的類:HttpGet,HttpHead,HttpPost,HttpPut,HttpDelete,HttpTrace和HttpOptions去完成。

  請求的URI是統一資源定位符,它標識了應用於哪個請求之上的資源,也即我們想要請求的接口地址。HTTP請求的URI包含一個協議模式,主機名稱,可選的端口,資源路徑,可選的查詢和可選的片段。比如上例中這個天氣預報的URI:

String uri = "http://weather.51wnl.com/weatherinfo/GetMoreWeather?cityCode=101010100&weatherType=0"

HttpGet httpget = new HttpGet(uri);


  HttpClient提供很多工具方法來簡化創建和修改執行URI。
  URI也可以編程來拼裝:

    URI uri = URIUtils.createURI("http", "weather.51wnl.com", -1, "/weatherinfo/GetMoreWeather","cityCode=101010100&weatherType=0", null);
    HttpGet httpget = new HttpGet(uri);
    System.out.println(httpget.getURI());

  輸出內容爲:

 
 http://weather.51wnl.com/weatherinfo/GetMoreWeather?cityCode=101010100&weatherType=0


  查詢字符串也可以從獨立的參數中來生成:

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("cityCode", "101010100"));
    qparams.add(new BasicNameValuePair("weatherType", "0"));
    URI uri = URIUtils.createURI("http", "weather.51wnl.com", -1, "/weatherinfo/GetMoreWeather",
    URLEncodedUtils.format(qparams, "UTF-8"), null);
    HttpGet httpget = new HttpGet(uri);
    System.out.println(httpget.getURI());


  輸出內容爲:
http://weather.51wnl.com/weatherinfo/GetMoreWeather?cityCode=101010100&weatherType=0

說明:URLEncodedUtils用於轉換中文爲UTF-8,防止中文亂碼。


對於Post提交,參數通過HttpEntity對象進行承載:


List<NameValuePair> formParams = new ArrayList<NameValuePair>();  
formParams.add(new BasicNameValuePair("cityCode", "101010100"));  
formParams.add(new BasicNameValuePair("weatherType", "0"));         
HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");  
   
HttpPost request = new HttpPost(“http://weather.51wnl.com/weatherinfo/GetMoreWeather”);  
request.setEntity(entity); 

說明:定義了一個NameValuePair類型的list集合,NameValuePair顧名思義名值對,多處用於Java像url發送Post請求。即這裏我們在發送post請求時用該list來存放參數。

響應

  HttpClient程序包對於HTTP響應的處理較之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();   

    // 或者
    String resultBody = EntityUtils.toString(entity, “utf-8”);


小結

   對HttpClient的請求和響應過程有了清晰的認識,這也是在http中最常用的功能,從上面的代碼中我們還可以看到url還是可以在進行抽象封裝的,後面繼續對get和post方法進行封裝。

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