我正在使用 Unirest(java 版本)发出 GET 和 POST 请求。但是在访问 SSL 加密站点时遇到问题,因为我的程序位于公司网络后面,并且网络管理员为我设置了防火墙映射。例如foobar.com
映射到56.1.89.12:4444
. 但是当我向地址提出请求时,我会收到以下 ssl 证书错误:
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
。所以我使用
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;
}
主要思想取自Ignoring SSL certificate in Apache HttpClient 4.3
但这仍然不起作用。有什么建议吗?