tinguo002

 

避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常

/**解决办法**
* 1添加一个方法
* 2调用这个方法生成一个新的httpClient对象
**/



import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpUtils
{
    
private HttpClient httpClient;
    
public HttpUtils()
    
{
        httpClient 
= null;
    }


    
public void openConnection()
    
{
        httpClient 
= new DefaultHttpClient();
      
  httpClient = getSecuredHttpClient(httpClient
    });
        


    
    
/**
     * 避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常
     * 不用导入SSL证书
     * 
     * 
@author shipengzhi(shipengzhi@sogou-inc.com)
     * 
     
*/

    
private static DefaultHttpClient getSecuredHttpClient(HttpClient httpClient) {
        
final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};
        
try {
            SSLContext ctx 
= SSLContext.getInstance("TLS");
            X509TrustManager tm 
= new X509TrustManager() {
                @Override
                
public X509Certificate[] getAcceptedIssuers() {
                    
return _AcceptedIssuers;
                }


                @Override
                
public void checkServerTrusted(X509Certificate[] chain,
                        String authType) 
throws CertificateException {
                }


                @Override
                
public void checkClientTrusted(X509Certificate[] chain,
                        String authType) 
throws CertificateException {
                }

            }
;
            ctx.init(
nullnew TrustManager[] { tm }new SecureRandom());
            SSLSocketFactory ssf 
= new SSLSocketFactory(ctx,
                    SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm 
= httpClient.getConnectionManager();
            SchemeRegistry sr 
= ccm.getSchemeRegistry();
            sr.register(
new Scheme("https"443, ssf));
            
return new DefaultHttpClient(ccm, httpClient.getParams());
        }
 catch (Exception e) {
            System.out.println(
"=====:=====");
            e.printStackTrace();
        }

        
return null;
    }

}



欢迎大家访问我的个人网站 萌萌的IT人

posted on 2014-04-09 17:34 一堣而安 阅读(974) 评论(0)  编辑  收藏 所属分类: java


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿(1)

随笔分类

随笔档案

收藏夹

搜索

最新评论

阅读排行榜

评论排行榜