您好,欢迎访问代理记账网站
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

HttpClient请求Https证书问题解决

本地使用HttpClient请求https时没有问题,但是放到服务器上,运行出现报错,出现异常为:

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

通过查阅网上资料,将解决方案整如下:

1.通过在服务器端安装证书

步骤:
1.现在指定的https链接下载证书,保存为.cer文件
2.双击.cer文件安装即可

但是,在按照以上步骤使用时,还是会出现异常,这里又通过查阅资料,了解到java的jdk用于自己的证书库,在使用时,需要将证书安装到jdk默认的证书库中,这里步骤大致如下:
1.进入jdk–>jre–>lib–>security目录下
2.cmd,并执行以下命令

keytool -import -alias kdcert -file E:\cert\kd.cert.cer -keystore cacerts -trustcacerts

alias :证书别名,用于查询证书
file :证书所在路径
-keystore cacerts -trustcacerts:固定写法

这种方法原则上是可行的,但是由于我的服务器不能装JDK环境,只能通过指定jre的方式运行jar包,而通过这种方式必须制定到jdk安装目录,这种方式因此也不考虑了

2.在代码段添加信任所有证书

这里采用在发送https请求前,对https证书进行全部信任,代码如下,亲测有效。

package com.focusmedis.FIM.communication;

import com.focusmedis.FIM.utils.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.mapping.ResultMap;
import org.springframework.stereotype.Service;

import javax.net.ssl.SSLContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HttpSend {

    private static CloseableHttpClient httpClient;

    /**
     * 信任SSL证书
     */
    static {
        try {
            SSLContext sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
            RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();
            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * post请求
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map<String, String> params) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        try {
            List<NameValuePair> pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList<>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
            }
            HttpPost httpPost = new HttpPost(url);
            if (pairs != null && pairs.size() > 0) {
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, "utf-8"));
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient is error status code :"
                        + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * post请求 发送json格式的报文 StringEntity
     * @param url
     * @param jsonString
     * @return
     */
    public static Map<String,Object> doPost(String url, String jsonString) {
        Map<String,Object> resultMap = new HashMap<>();
        if (StringUtils.isBlank(url)) {
            return null;
        }
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity stringEntity = new StringEntity(jsonString, "utf-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);

            //这里新增对进得请求头的判断
            Map<String, Object> datamap = JsonUtils.JsonToMapObj(jsonString);
            if (datamap.containsKey("api")) {
                String api = (String) datamap.get("api");
                httpPost.setHeader("api", api);
            }

            if (datamap.containsKey("accessTokenStr")) {
                String accessTokenStr = (String) datamap.get("accessTokenStr");
                httpPost.setHeader("accessToken", accessTokenStr);
            }

            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient is error status code :"
                        + statusCode);
            }
            HttpEntity entity = response.getEntity();

            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");

                resultMap.put("statuscode", Integer.toString(statusCode));
                resultMap.put("conResult",result);
            }
            EntityUtils.consume(entity);
            response.close();
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}


分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进