httpClient忽略https证书验证

直接上代码

    public static String post(String url, String head, String body) throws Exception {

        // 创建httpClient的默认实例
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 忽略https证书验证
        httpClient = (CloseableHttpClient) wrapClient(httpClient);

        try {

            // 创建POST请求
            HttpPost post = new HttpPost(url);

            // 设置请求头
            post.addHeader("reqParameter", head);
            post.addHeader("Content-Type", "text/plain");

            // 设置请求体
            StringEntity entity = new StringEntity(body, "utf-8");
            post.setEntity(entity);

            // 执行POST请求
            CloseableHttpResponse response = httpClient.execute(post);
            if (response != null) {
                log.info("请求成功, 响应状态: {}", response.getStatusLine().getStatusCode());
                HttpEntity httpEntity = response.getEntity();
                // 如果返回的内容不为空
                if (httpEntity != null) {
                    return EntityUtils.toString(httpEntity, "UTF-8");
                }
            }

        } catch (Exception e) {
            log.error("请求异常: e = {}", e);
            e.printStackTrace();
        } finally {
            httpClient.close();
        }
        return null;
    }
    /**
     * description 忽略https证书验证
     *
     * @author yanzy
     * @version 1.0
     * @date 2021/9/8 14:42
     */
    public static HttpClient wrapClient(HttpClient base) {
        try {
            SSLContext ctx = SSLContext.getInstance("SSL");
            X509TrustManager tm = new X509TrustManager() {

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] arg0,
                                               String arg1) throws CertificateException {
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).build();
            return httpclient;
        } catch (Exception ex) {
            ex.printStackTrace();
            return HttpClients.createDefault();
        }
    }

你可能感兴趣的:(https,http,java)