Apache HttpComponents Client 4.0快速入门/升级-1.GET方法访问网页(转)

本文对比了Apache HttpClient 3.1与4.0版本中GET方法的实现方式,并提供了示例代码。HttpClient 4.0与3.1在API设计上存在较大差异,导致代码不兼容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载自邬贼博客,原文地址:http://blog.youkuaiyun.com/inkfish/archive/2009/11/02/4757380.aspx

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();
}
}
}


本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/inkfish/archive/2009/11/02/4757380.aspx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值