继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

SSLException错误解决方案

慕无忌5226852
关注TA
已关注
手记 2
粉丝 1
获赞 0

private static DefaultHttpClient getHttpClient() {

        try {

            // 禁止https证书验证

            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

            trustStore.load(null, null);

            SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);

            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);//运行所有的hostname验证

 

            HttpParams params = new BasicHttpParams();

            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

 

            // 禁用Cookie2请求头

            HttpClientParams.setCookiePolicy(params, CookiePolicy.RFC_2109);

            HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY);

            HttpClientParams.setCookiePolicy(params, CookiePolicy.NETSCAPE);

 

            SchemeRegistry registry = new SchemeRegistry();

            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

            registry.register(new Scheme("https", sf, 443));

 

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

 

            HttpConnectionParams.setConnectionTimeout(params, 3000);

            HttpConnectionParams.setSoTimeout(params, 5000);

 

            return new DefaultHttpClient(ccm, params);

        } catch (Exception e) {

            HttpParams httpParams = new BasicHttpParams();

            HttpConnectionParams.setConnectionTimeout(httpParams, 3000);

            HttpConnectionParams.setSoTimeout(httpParams, 5000);

 

            return new DefaultHttpClient(httpParams);

        }

    }

通过上述方法获取得到的DefaultHttpClient ,通过该HttpClient再次进行网络请求就能绕过证书验证。该方法需要导入Apache的网络包:org.apache.http.legacy.jar

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP