使用 apache HTTPS 库时无法在 Java 中创建客户端
Not able to create client in Java while using apache HTTPS libraries
我正在开发一个应用程序,我必须将请求发送到另一个服务器 运行。每当我尝试创建客户端以便将我的 API 请求发送到服务器时,它都卡在那里。它也不会抛出异常并且不会被执行。该线程没有做任何事情就死了。我通过在每一行之后放置记录器进行了大量调试,发现 SSL 构建行有问题。
如果我尝试从本地机器执行相同的代码,它会被干净地执行,但是从我的应用程序,它会失败。有人可以让我知道确切的是什么 issue.Here 是我为创建 client.I 编写的代码,认为这个问题与证书有关,但在验证方法中,它说的是将所有内容设置为 true。
private HttpClient createClient() throws Exception {
X509TrustManager x509TrustManager = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
};
TrustManager[] trustManagers = new TrustManager[] {x509TrustManager};
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, trustManagers, new SecureRandom());
// code works fine till here and after that this thread just dies.
return HttpClients.custom().setSSLHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}).setSSLContext(sslContext).build();
}
问题出在 httpcore 版本的版本上。因为我使用的 httpclient 版本大于 4.5,而我的 httpcore 版本小于 4。代码没有问题。如果有人使用 apache 库创建客户端,请确保您使用的是更新的版本。
我正在开发一个应用程序,我必须将请求发送到另一个服务器 运行。每当我尝试创建客户端以便将我的 API 请求发送到服务器时,它都卡在那里。它也不会抛出异常并且不会被执行。该线程没有做任何事情就死了。我通过在每一行之后放置记录器进行了大量调试,发现 SSL 构建行有问题。 如果我尝试从本地机器执行相同的代码,它会被干净地执行,但是从我的应用程序,它会失败。有人可以让我知道确切的是什么 issue.Here 是我为创建 client.I 编写的代码,认为这个问题与证书有关,但在验证方法中,它说的是将所有内容设置为 true。
private HttpClient createClient() throws Exception {
X509TrustManager x509TrustManager = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
};
TrustManager[] trustManagers = new TrustManager[] {x509TrustManager};
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, trustManagers, new SecureRandom());
// code works fine till here and after that this thread just dies.
return HttpClients.custom().setSSLHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}).setSSLContext(sslContext).build();
}
问题出在 httpcore 版本的版本上。因为我使用的 httpclient 版本大于 4.5,而我的 httpcore 版本小于 4。代码没有问题。如果有人使用 apache 库创建客户端,请确保您使用的是更新的版本。