HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供支持 HTTP 协议的客户端编程工具包
HttpClient: http://hc.apache.org/httpclient-3.x/
HttpClient入门: http://www.ibm.com/developerworks/cn/opensource/os-httpclient/
示例:通过Get方法取得百度首页内容
![](http://static.oschina.net/uploads/space/2013/0121/145459_yCxy_154489.png)
@SuppressWarnings("serial")
public class HttpClientTest extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
// 构造HttpClient的实例
HttpClient httpClient = new HttpClient();
// 创建GET方法的实例
GetMethod getMethod = new GetMethod("http://www.baidu.com");
// 使用系统提供的默认的恢复策略
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
try{
int statusCode = httpClient.executeMethod(getMethod);
if(statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: "
+ getMethod.getStatusLine());
}
// 读取内容
byte[] responseBody = getMethod.getResponseBody();
// 处理内容
out.println(new String(responseBody));
}catch(HttpException e) {
System.out.println("Please check your provided http address!");
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}finally {
getMethod.releaseConnection();
}
}
}
启动服务器通过http://localhost:8080/HttpClientTest/HttpClientTest访问就可以看到百度首页的画面
HttpComponents
HttpComponents: http://hc.apache.org/
httpclient项目从commons子项目挪到了HttpComponents子项目下
The Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules, which offer better performance and more flexibility.
示例: 通过Get方法取得百度首页内容,从apache的HttpComponents子项目下下载所需的jar包
@SuppressWarnings("serial")
public class HttpComponentsTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html; charset=utf-8");
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.baidu.com");
try {
PrintWriter out = resp.getWriter();
HttpResponse httpResp = httpclient.execute(httpGet);
int statusCode = httpResp.getStatusLine().getStatusCode();
if(statusCode == 200) {
out.println(EntityUtils.toString(httpResp.getEntity()));
}
}catch(Exception e) {
e.printStackTrace();
}finally {
httpGet.releaseConnection();
}
}
}