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();
版权声明

本站文章、图片、视频等(除转载外),均采用知识共享署名 4.0 国际许可协议(CC BY-NC-SA 4.0),转载请注明出处、非商业性使用、并且以相同协议共享。

© 空空博客,本文链接:https://www.yeetrack.com/?p=660