DefaultHttpClient 报错https peer not authenticated解决

使用apache的httpcomponents包,能够很方便的使用java来发送http请求,与服务器交互。其中的DefaultHttpClient是我们发送http请求的客户端类,它支持http和https。如果要使用https的话,在测试环境中经常因为证书无效,而报错Exception in thread “main” javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated。这时我们可以指定DefaultHttpClient忽略证书认证错误,继续进行http交互,主要代码如下:

/**
 * 参数base就是我们创建的DefaultHttpClient对象
 ** /
public static HttpClient wrapClient(HttpClient base) 
{
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException
            {
                // TODO Auto-generated method stub

            }

            public void checkServerTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException
            {
                // TODO Auto-generated method stub

            }

            public X509Certificate[] getAcceptedIssuers()
            {
                // TODO Auto-generated method stub
                return null;
            }

        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        //设置要使用的端口,默认是443
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

在使用时,直接调用wrapClient()方法即可。

DefaultHttpClient httpClient = wrapClient(new DefaultHttpClient());
HttpGet get = new HttpGet("https://somesite.domain.com");
HttpResponse response = httpClient.execute(get);
String result = EntityUtils.toString(response.getEntity());
System.out.println(resultString);
httpClient.getConnectionManager().shutdown();

发表评论

电子邮件地址不会被公开。 必填项已用*标注

(Spamcheck Enabled)