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 = "http://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);
return client.execute(httpget, new basicresponsehandler());
client.getconnectionmanager().shutdown();