Recently, when using httpclient to connect with the third-party SMS interface, a certificate invalidation error was reported during the local test.
1. Post request of Encapsulated HttpClient:
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) // Set the connection timeout, in milliseconds
.setConnectionRequestTimeout(1000)
.setSocketTimeout(5000) // timeout for requesting data, in milliseconds
.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;
}
However, an error will be reported when accessing some self signed HTTPS requests. This problem is caused by the invalid link certificate, because the self signed certificate will be recognized as an unsafe link.
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
2. Solutions
- Set the security certificate of jdk according to the online method -> No work
- Set maven to ignore the certificate checksum -> no work
- Yml file configuration httpclient ignore SSL checksum, seems to have no effect.
- Finally used the method of modifying the code, the principle is also to ignore the certificate checksum, but the code produced the effect, it is estimated that the construction is related to the Httpclient.
Modify the original code
// Ignore SSL Security Certification
**SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(
SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
NoopHostnameVerifier.INSTANCE);**
try (CloseableHttpClient client = **HttpClients.custom().setSSLSocketFactory(scsf)**
.setDefaultRequestConfig(requestConfig)
.setRetryHandler(myRetryHandler)
.build()) {
Read More:
- [Solved] HttpPost Call https Interface error: PKIX path building failed
- [Solved] maven Import Error: PKIX path building failed
- Maven (http://repo1.maven.org/maven2/): Failed to transfer file and PKIX path building failed: sun.secu
- [PROJECT] itdage java to get the weather and send text messages
- Request processing failed; nested exception is java.lang.NullPointerException or UnsatisfiedDependencyE
- [Solved] Java.lang.IllegalStateException: getReader() has already been called for this request
- [Solved] MultipartException: Failed to parse multipart servlet request; nested exception is java.lang.Runtime
- [Solved] Tomcat configurate HTTPS error: java.net.SocketException: Permission denied
- [Solved] IDEA springboot Startup Error: java.lang.UnsatisfiedLinkError: no tcnative-1 in java.library.path
- [Solved] IDEA jsp File Error: pageContext.setAttribute(“APP_PATH“,request.getContextPath());
- Asynchronous processing of HTTP request by Java_ Method 1: through callable
- Asynchronous processing of HTTP request by Java_ Method 2: through deferredresult
- keytool error: java.lang.Exception: Input not an X.509 certificate
- JAVA Connect MYSQL Error: Path does not chain with any of the trust anchors
- [Solved] the resource is not on the build path of a java project
- [Solved] Java XXX: unable to find topic engine in module path
- SpringCloud Use openFeign Multipartfile to Upload Files Error: Current request is not a multipart request
- [Solved] Spring Kafka Send Error in specifies partition: Topic radar not present in metadata after 60000
- [Solved] java: Compilation failed: internal java compiler error
- [Solved] Java: compilation failed: internal java compiler error