1、获取httpclient,忽略证书认证
public static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有证书
public boolean isTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
return true;
}
}).build();
// 创建主机名验证器,用于绕过主机名验证
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
// 创建 SSL 连接套接字工厂,将自定义的 SSL 上下文和主机名验证器应用于 HTTPS 连接
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
// 创建自定义的 CloseableHttpClient 实例,将 SSL 连接套接字工厂应用于 HTTP 客户端
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
2、使用put请求调用
public static String put(String url, Map<String, String> header, String param) throws Exception {
String result = "";
StringEntity entity = new StringEntity(param, "utf-8");
CloseableHttpClient httpClient = null;
try {
httpClient = createSSLClientDefault();
HttpPut httpPut = new HttpPut(url);
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpPut.addHeader(entry.getKey(), entry.getValue());
}
}
if (entity != null) {
entity.setContentType("application/json; charset=utf-8");
httpPut.setEntity(entity);
}
LogUtil.info("开始请求https接口:" + url );
HttpResponse httpResponse = httpClient.execute(httpPut);
LogUtil.info("put请求返回httpResponse结果:" + httpResponse);
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity, "UTF-8");
LogUtil.info("put请求返回结果:" + result);
} catch (Exception e) {
throw e;
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return result;
}