96、https取消证书验证
public static Map<String, String> getApi(String url, Map insertMap) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
// 创建SSL上下文,忽略证书验证
SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial((chain, authType) -> true);
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE);
Map<String, String> map = new HashMap<>();
// 最多尝试请求次数
int maxRetries = 3;
int retry = 1;
while (retry < maxRetries) {
// 发起请求
try (CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslSocketFactory)
.build()) {
// try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建 URIBuilder 对象
URIBuilder uriBuilder = new URIBuilder(url);
insertMap.forEach((k, v) -> {
// 添加参数
uriBuilder.addParameter(k.toString(), v.toString());
});
// 构建 URI
URI newUrl = uriBuilder.build();
System.out.println("查询内容" + newUrl.getQuery());
// 创建 HttpGet 请求
HttpGet httpGet = new HttpGet(newUrl);
SslUtils.ignoreSsl();
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
// 释放连接
EntityUtils.consume(entity);
map.put("code", "200");
map.put("message", "接口访问成功");
map.put("responseBody", responseBody);
}
return map;
} catch (SocketTimeoutException e) {
e.printStackTrace();
map.put("code", "500");
map.put("message", "接口访问超时");
} catch (Exception e) {
e.printStackTrace();
map.put("code", "500");
map.put("message", "接口访问失败");
}
try {
Thread.sleep(20 * 1000);
} catch (Exception e) {
e.printStackTrace();
}
retry++;
}
// 如果超过最大重试次数仍然未成功,则直接返回错误信息
if (retry == maxRetries) {
map.put("code", "500");
map.put("message", "尝试请求多次仍然失败,无法访问接口");
}
return map;
}