我正在使用 Apache HttpClient 在某个 url 上发送 https POST。
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);
我得到:
javax.net.ssl.SSLException: hostname in certificate didn't match: <*.*.*.*> != <*.url
现在经过搜索,我在stackoverflow上找到了解决方案:
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
HttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
POST 已成功完成。
但我不明白这里发生了什么!我的连接仍然安全吗?这是正确的解决方案吗?如果没有,最好的解决方案是什么?