Java使用HttpClient发送Https请求证书失效:PKIX path building failed:
public static Map<String, Object> postReq(String URL, Map<String, Object> paramMap, Map<String, String> headers) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(2000) // 设置连接超时时间,单位毫秒
.setConnectionRequestTimeout(1000)
.setSocketTimeout(5000) // 请求获取数据的超时时间,单位毫秒
.build();
HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
return false;
}
};
try (CloseableHttpClient client = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setRetryHandler(myRetryHandler)
.build()) {
HttpPost httpPost = new HttpPost(URL);
if (paramMap != null) {
JSONObject paramJson = new JSONObject(paramMap);
StringEntity paramEntity = new StringEntity(paramJson.toString(), "UTF-8");
paramEntity.setContentType("application/json; charset=utf-8");
httpPost.setEntity(paramEntity);
}
httpPost.setConfig(requestConfig);
if (headers != null && !headers.isEmpty()) {
for (String key : headers.keySet()) {
String value = headers.get(key);
httpPost.setHeader(key, value);
}
}
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseStr = EntityUtils.toString(entity, "UTF-8");
if (responseStr.isEmpty()) {
responseStr = "{}";
}
int statusCode = response.getStatusLine().getStatusCode();
if (HttpServletResponse.SC_OK == statusCode) {
try {
JSONObject dataJson = (JSONObject) JSONObject.parse(responseStr);
map = new HashMap<>(dataJson);
} catch (Exception e) {
map.put("reponse", responseStr);
}
} else {
return map;
}
}
response.close();
}
return map;
}