终于建了一个自己个人小站:https://huangtianyu.gitee.io,以后优先更新小站博客,欢迎进站,O(∩_∩)O~~
现在网站用https的服务器越来越多了,在编写程序的时候往往会遇到证书验证错误。也就是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