閱讀997 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Apache HttpComponents Client 4.0快速入門/升級-1.GET方法訪問網頁

 Apache HttpComponents Client 4.0已經發布多時,httpclient項目從commons子項目挪到了HttpComponents子項目下,httpclient3.1和httpcilent4.0無法做到代碼向後兼容,升級比較麻煩。我在做項目之餘找時間研究了一下,寫了一套3.1與4.0對比的代碼,不求麵麵俱到,但求簡單易懂。如果代碼用到真實項目中,還需要考慮諸如代理、Header、異常處理之類的問題。

 

Http GET方法得到www.g.cn的源碼:

import java.io.IOException; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; public class GetSample { /** * @param args * @throws IOException * @throws HttpException */ public static void main(String[] args) throws HttpException, IOException { String url = "https://www.g.cn/"; System.out.println(url); System.out.println("Visit google using Apache commons-httpclient 3.1:"); System.out.println(get3(url)); System.out.println("Visit google using Apache HttpComponents Client 4.0:"); System.out.println(get4(url)); } /** 使用Apache commons-httpclient 3.1,GET方法訪問網頁 */ public static String get3(String url) throws HttpException, IOException { org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient(); GetMethod getMethod = new GetMethod(url); try { if (httpClient.executeMethod(getMethod) != HttpStatus.SC_OK) { System.err.println("Method failed: " + getMethod.getStatusLine()); } return getMethod.getResponseBodyAsString(); } finally { getMethod.releaseConnection(); } } /** 使用Apache HttpComponents Client 4.0,GET方法訪問網頁 */ public static String get4(String url) throws ClientProtocolException, IOException { org.apache.http.client.HttpClient client = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); try { return client.execute(httpget, new BasicResponseHandler()); } finally { client.getConnectionManager().shutdown(); } } }

最後更新:2017-04-02 04:01:42

  上一篇:go MVC架構探究及其源碼實現(2)-核心組件定義
  下一篇:go 敏捷軟件開發的含義