如何使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();
makeClient
方法 MyHttpClient
是:
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?
推荐答案
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
Unirest.setHttpClient(httpclient);
这对我有用
这篇关于如何使Unirest(java)忽略证书错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!