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

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

HttpClient4.x支持自定义SSL上下文,这个功能非常实用,我们可以利用这一点非常轻松地实现获取某些需要证书后才能正常浏览的网页的需要。

下面请看范例代码:

package cn.ysh.studio.crawler.httpclient;import java.io.File;import java.io.FileInputStream;import java.security.KeyStore;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.conn.scheme.Scheme;import org.apache.http.conn.ssl.SSLSocketFactory;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;/**
 * 演示如何使用自定义的SSL上下文创建HTTPS安全连接
 * 
 * @author Shenghany
 * @date 2013-5-19
 */publicclassClientCustomSSL{publicfinalstaticvoid main(String[] args)throwsException{DefaultHttpClient httpclient =newDefaultHttpClient();try{//创建密钥存储器KeyStore trustStore  =KeyStore.getInstance(KeyStore.getDefaultType());//加载证书信息FileInputStream instream =newFileInputStream(newFile("my.keystore"));try{
                trustStore.load(instream,"nopassword".toCharArray());}finally{try{ instream.close();}catch(Exception ignore){}}//创建SSL工厂SSLSocketFactory socketFactory =newSSLSocketFactory(trustStore);//创建HTTPS模式Scheme sch =newScheme("https",443, socketFactory);//注册HTTPS模式
            httpclient.getConnectionManager().getSchemeRegistry().register(sch);//创建GET请求HttpGet httpget =newHttpGet("https://localhost");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:15  刺猬的温驯  阅读(601)  评论(0)    收藏  举报