HttpClient与HttpComponents

HttpClient

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供支持 HTTP 协议的客户端编程工具包
HttpClient: http://hc.apache.org/httpclient-3.x/
HttpClient入门: http://www.ibm.com/developerworks/cn/opensource/os-httpclient/

示例:通过Get方法取得百度首页内容

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

转载于:https://my.oschina.net/xiaomaoandhong/blog/103491

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值