美文网首页
https请求证书异常

https请求证书异常

作者: 陌椰_5702 | 来源:发表于2019-08-26 22:47 被阅读0次

今天遇到一个问题,很是崩溃,处理了一天,真的是处理了一天。。。。。

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

httpclient调用https接口报错,先是证书不行,接下来,变成了域名不匹配,找了各种办法治不好!

不说了,下面直接上代码

public static String httpPostWithString(String url,String jsonParam,Integer timeOut)throws KeyManagementException, NoSuchAlgorithmException {

SSLContext ctx= SSLContext.getInstance("TLSv1.2");

ctx.init(null,null,null);

CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(ctx)).build();

HttpPost httpPost =new HttpPost(url);

String strResult =null;

try {

//httpPost.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8));

        HttpEntity httpEntity =new StringEntity(jsonParam, ContentType.APPLICATION_JSON);

httpPost.setEntity(httpEntity);

/*连接超时*/

        if (null != timeOut) {

RequestConfig requestConfig = RequestConfig.custom()

.setConnectTimeout(timeOut).setConnectionRequestTimeout(timeOut)

.setSocketTimeout(timeOut).build();

httpPost.setConfig(requestConfig);

}

HttpResponse httpResponse = httpClient.execute(httpPost);

if (httpResponse.getStatusLine().getStatusCode() ==200) {

strResult = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");//获得返回的结果

        }

}catch (IOException e) {

e.printStackTrace();

}finally {

try {

httpClient.close();//释放资源

            }catch (IOException e) {

e.printStackTrace();

}

}

return strResult.toString();

}


然后你发现和我一样的写法可能还会报错,接下来,重点来了,请注意httpclient的依赖

<dependency>

<groupId>org.apache.httpcomponents</groupId>

<artifactId>httpclient</artifactId>

<version>4.4.1</version>

</dependency>

协议可以在firefox上查看:

谢谢大家!

相关文章

网友评论

      本文标题:https请求证书异常

      本文链接:https://www.haomeiwen.com/subject/hjujectx.html