gpt4 book ai didi

Java SSLException : hostname in certificate didn't match

转载 作者:IT老高 更新时间:2023-10-28 20:46:22 25 4
gpt4 key购买 nike

我一直在使用以下代码连接到谷歌的一项服务。这段代码在我的本地机器上运行良好:

HttpClient client=new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");
post.setEntity(new UrlEncodedFormEntity(myData));
HttpResponse response = client.execute(post);

我把这段代码放在了一个生产环境中,它阻止了 Google.com。根据要求,他们通过允许我访问 IP 来允许与 Google 服务器通信:74.125.236.52 - 这是 Google 的 IP 之一。我也编辑了我的主机文件以添加此条目。

我仍然无法访问 URL,我想知道为什么。所以我把上面的代码换成了:

HttpPost post = new HttpPost("https://74.125.236.52/accounts/ClientLogin");

现在我收到这样的错误:

javax.net.ssl.SSLException: hostname in certificate didn't match: <74.125.236.52> != <www.google.com>

我猜这是因为 Google 有多个 IP。我不能要求网络管理员允许我访问所有这些 IP - 我什至可能无法获得整个列表。

我现在该怎么办? Java级别是否有解决方法?还是完全掌握在网络人手中?

最佳答案

您也可以尝试设置 HostnameVerifier,如 here 所述。 .这对我来说可以避免这个错误。

// Do not do this in production!!!
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

DefaultHttpClient client = new DefaultHttpClient();

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);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

// Example send http request
final String url = "https://encrypted.google.com/";
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);

关于Java SSLException : hostname in certificate didn't match,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7256955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com