手记

SSLException错误解决方案

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

0人推荐
随时随地看视频
慕课网APP