当前位置:   article > 正文

javax.net.ssl.SSLException:hostname in certificate didn't match

javax.net.ssl.SSLException:hostname in certificate didn't match

终于建了一个自己个人小站:https://huangtianyu.gitee.io,以后优先更新小站博客,欢迎进站,O(∩_∩)O~~

现在网站用https的服务器越来越多了,在编写程序的时候往往会遇到证书验证错误。也就是SSLException错误。下面给出解决方案:

  1. private static DefaultHttpClient getHttpClient() {
  2. try {
  3. // 禁止https证书验证
  4. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  5. trustStore.load(null, null);
  6. SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
  7. sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);//运行所有的hostname验证
  8. HttpParams params = new BasicHttpParams();
  9. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  10. HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
  11. // 禁用Cookie2请求头
  12. HttpClientParams.setCookiePolicy(params, CookiePolicy.RFC_2109);
  13. HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY);
  14. HttpClientParams.setCookiePolicy(params, CookiePolicy.NETSCAPE);
  15. SchemeRegistry registry = new SchemeRegistry();
  16. registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  17. registry.register(new Scheme("https", sf, 443));
  18. ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
  19. HttpConnectionParams.setConnectionTimeout(params, 3000);
  20. HttpConnectionParams.setSoTimeout(params, 5000);
  21. return new DefaultHttpClient(ccm, params);
  22. } catch (Exception e) {
  23. HttpParams httpParams = new BasicHttpParams();
  24. HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
  25. HttpConnectionParams.setSoTimeout(httpParams, 5000);
  26. return new DefaultHttpClient(httpParams);
  27. }
  28. }
通过上述方法获取得到的DefaultHttpClient ,通过该HttpClient再次进行网络请求就能绕过证书验证。该方法需要导入Apache的网络包:org.apache.http.legacy.jar

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/650836
推荐阅读
相关标签
  

闽ICP备14008679号