java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java忽略ssl证书认证

java中调用https请求忽略ssl证书认证代码示例

作者:新时代农民~

在网络请求中经常会遇到需要忽略证书认证的情况,这篇文章主要介绍了java中调用https请求忽略ssl证书认证的相关资料,文中通过代码示例介绍的非常详细,需要的朋友可以参考下

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

总结 

到此这篇关于java中调用https请求忽略ssl证书认证的文章就介绍到这了,更多相关java调用https请求忽略ssl认证内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文