君子博学而日参省乎己 则知明而行无过矣

博客园 首页 新随笔 联系 订阅 管理

最近Apache HttpClient发布了最新的4.3版本,据说有很多的改进,加入了新的设计思想和理念,使API更加简洁有力,闲来无事,做个Demo尝尝鲜。

在以前的3.x版本中,HttpClient就已经支持HTTPS连接了,但是代码写的比较多,而且用起来感觉挺别扭的,同样的功能,到了4这里,明显得简单清爽多了。

如下是来自官方的一个例子,稍加改造,并翻译了注释:  

package cn.ysh.studio.crawler.httpclient;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;/**
 * 演示如何使用HttpClient向需要身份验证的目标服务器发送HTTP请求
 * 
 * @author Shenghany
 * @date 2013-5-19
 */publicclassClientAuthentication{publicstaticvoid main(String[] args)throwsException{DefaultHttpClient httpclient =newDefaultHttpClient();try{//添加证书
            httpclient.getCredentialsProvider().setCredentials(newAuthScope("localhost",443),newUsernamePasswordCredentials("username","password"));//创建GET请求HttpGet httpget =newHttpGet("https://localhost/protected");System.out.println("executing request"+ httpget.getRequestLine());//执行请求HttpResponse response = httpclient.execute(httpget);//获得响应实体HttpEntity entity = response.getEntity();System.out.println("----------------------------------------");System.out.println(response.getStatusLine());if(entity !=null){System.out.println("Response content length: "+ entity.getContentLength());}//销毁实体EntityUtils.consume(entity);}finally{// 当不再需要HttpClient实例时,关闭连接管理器以确保释放所有占用的系统资源
            httpclient.getConnectionManager().shutdown();}}}
posted on 2013-07-25 04:07  刺猬的温驯  阅读(848)  评论(0)    收藏  举报