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的執行參數使用。
l HTTP請求
當然在所有請求中最常用的還是GET與POST兩種請求,創建請求的方式如下:
HttpUriRequest request = newHttpPost("http://localhost/index.html");
HttpUriRequest request = newHttpGet(“http://127.0.0.1:8080/index.html”);
HTTP請求格式告訴我們,有兩種方式可以為request提供參數:request-line方式與request-body方式。
? request-line方式是指在請求行上通過URI直接提供參數。
(1)可以在生成request對象時提供帶參數的URI,如:
HttpUriRequest request = newHttpGet("http://localhost/index.html?param1=value1¶m2=value2");
(2)HttpClient程序包還提供了URIUtils工具類,可以通過它生成帶參數的URI,如:
URI uri =URIUtils.createURI("http", "localhost", -1,"/index.html",
"param1=value1¶m2=value2", null);
HttpUriRequest request = newHttpGet(uri);
System.out.println(request.getURI());
上例的實例結果如下:
http://localhost/index.html?param1=value1¶m2=value2
(3)需要注意的是,如果參數中含有中文,需將參數進行URLEncoding處理,如:
String param ="param1=" + URLEncoder.encode("中國", "UTF-8") +"¶m2=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¶m2=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);
上例的實例結果如下:
http://localhost/index.html?param1=%E4%B8%AD%E5%9B%BD¶m2=value2
? 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¶m2=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);
l 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(); } }