java中调用https请求,忽略ssl证书认证 1、获取httpclient,忽略证书认证。2、使用put请求调用。

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 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 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;
 }

作者:新时代农民~原文地址:https://blog.csdn.net/qq_38399109/article/details/141566044

%s 个评论

要回复文章请先登录注册