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

避免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([email protected])
     * 
     
*/

    
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人

你可能感兴趣的:(避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常)