如何让 Unirest(java) 忽略证书错误 [英] how to make Unirest(java) ignore certificate error
问题描述
我正在使用 Unirest(java 版本)发出 GET 和 POST 请求.但是我在访问 SSL 加密站点时遇到了问题,因为我的程序位于公司网络之后,并且网络管理员为我设置了防火墙映射.例如 foobar.com
映射到 56.1.89.12:4444
.但是当我向该地址提出请求时,我会收到以下 ssl 证书错误:
I am using Unirest (java version) to make GET and POST request.But I encounter a problem when accessing SSL encrypted site , since my program is behind a corporate network and the network admin setup a firewall mapping for me. For example foobar.com
is mapped to 56.1.89.12:4444
. But when I make request to the address, I will received the following ssl certificate error:
com.mashape.unirest.http.exceptions.UnirestException: javax.net.ssl.SSLException: hostname in certificate didn't match: <56.1.89.12> != <www.foobar.com>
at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:131)
at com.mashape.unirest.request.BaseRequest.asString(BaseRequest.java:52)
我看到 Unirest
有使用自定义 httpclient
的高级配置.所以我使用
I see Unirest
has advance configuration to use custom httpclient
.So I use
Unirest.setHttpClient(MyHttpClient.makeClient());
HttpResponse<String> res = null;
try {
res = Unirest.get(urlstr).asString();
} catch (UnirestException e) {
e.printStackTrace();
}
String jsonstr = res.getBody();
MyHttpClient
的 makeClient
方法是:
public static HttpClient makeClient(){
SSLContextBuilder builder = new SSLContextBuilder();
CloseableHttpClient httpclient = null;
try {
// builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
builder.loadTrustMaterial(null, new TrustStrategy(){
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
});
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
builder.build());
httpclient = HttpClients.custom().setSSLSocketFactory(
sslsf).build();
System.out.println("custom httpclient called");
System.out.println(httpclient);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return httpclient;
}
主要思想取自 忽略 Apache HttpClient 4.3 中的 SSL 证书
但这仍然不起作用.有什么建议吗?
But still this didn't work.Any suggestions?
推荐答案
我正在使用 "com.konghq:unirest-java:2.3.14
I'm using "com.konghq:unirest-java:2.3.14"
现在有一个配置
Unirest.config().verifySsl(false);
这篇关于如何让 Unirest(java) 忽略证书错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!