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);
try {
return client.execute(httpget, new BasicResponseHandler());
} finally {
client.getConnectionManager().shutdown();
}
}
}