如何使Unirest(java)忽略证书错误

编程入门 行业动态 更新时间:2024-10-22 07:38:33
本文介绍了如何使Unirest(java)忽略证书错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用Unirest(java版本)来发出GET和POST请求。但是我在访问SSL加密站点时遇到问题,因为我的程序在公司网络后面,网络管理员为我设置了防火墙映射。例如 foobar 映射到 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 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.ssl.SSLException: hostname in certificate didn't match: <56.1.89.12> != <www.foobar> 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)忽略证书错误

本文发布于:2023-11-07 22:52:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567657.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:证书   错误   Unirest   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!