前两篇文章我们以实际代码讲解了如何使用使用代理服务器抓取网页(《HttpClient4.x通过代理服务器抓取网页》)和如何建立HTTPS安全连接(《HttpClient4.x客户端身份验证(HTTPS安全连接)》),本文将二者结合起来,以实际代码演示如何通过身份验证代理,在安全的连接通道中执行HTTP请求,即如何通过代理服务器进行身份认证并以HTTPS安全连接方式连接到目标服务器。
代码如下:

 

package cn.ysh.studio.crawler.httpclient;import org.apache.http.HttpEntity;import org.apache.http.HttpHost;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.conn.params.ConnRoutePNames;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;/**
 * 使用HttpClient执行HTTP请求,并通过需要身份验证的代理服务器建立一个安全(HTTPS)的连接
 * 
 * @author Shenghany
 * @date 2013-5-19
 */publicclassClientProxyAuthentication{publicstaticvoid main(String[] args)throwsException{DefaultHttpClient httpclient =newDefaultHttpClient();try{// 在代理服务器上安装证书
            httpclient.getCredentialsProvider().setCredentials(newAuthScope("localhost",8080),newUsernamePasswordCredentials("username","password"));//目标服务器HttpHost targetHost =newHttpHost("www.verisign.com",443,"https");//代理服务器HttpHost proxy =newHttpHost("localhost",8080);//设置代理服务器
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);//Get方式请求首页面HttpGet httpget =newHttpGet("/");System.out.println("executing request: "+ httpget.getRequestLine());System.out.println("via proxy: "+ proxy);System.out.println("to target: "+ targetHost);//执行请求HttpResponse response = httpclient.execute(targetHost, 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();}}}