java通过HttpClient方式实现https请求的工具类(绕过证书验证)

目录

一、引入依赖包

  • 引入相关依赖包

    java 复制代码
     <!--lombok用于简化实体类开发-->
     <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
     </dependency>
     <!--fastjson依赖-->
     <dependency>
         <groupId>com.alibaba</groupId>
         <artifactId>fastjson</artifactId>
         <version>2.0.32</version>
     </dependency>
     <!--httpclient依赖-->
      <dependency>
        <groupId>org.apache.httpcomponents</groupId>
         <artifactId>httpclient</artifactId>
         <version>4.5.2</version>
      </dependency>

二、HttpClient方式实现的https请求工具类

  • https工具类代码

    java 复制代码
    package com.xz.https;
    
    import com.alibaba.fastjson.JSONObject;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.http.HttpEntity;
    import org.apache.http.ParseException;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.config.Registry;
    import org.apache.http.config.RegistryBuilder;
    import org.apache.http.conn.socket.ConnectionSocketFactory;
    import org.apache.http.conn.socket.PlainConnectionSocketFactory;
    import org.apache.http.conn.ssl.NoopHostnameVerifier;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
    import org.apache.http.util.EntityUtils;
    import org.springframework.core.io.ClassPathResource;
    
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.TrustManagerFactory;
    import javax.net.ssl.X509TrustManager;
    import java.io.IOException;
    import java.security.KeyManagementException;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.Certificate;
    import java.security.cert.CertificateException;
    import java.security.cert.CertificateFactory;
    import java.security.cert.X509Certificate;
    
    
    /**
     * @Description HttpClient方式的 https工具类
     * @author xz
     */
    @Slf4j
    public class HttpsUtil {
    
        public static String post(String url, JSONObject content) throws Exception {
            String returnInfo = "";
            CloseableHttpResponse response = null;
            //getTrust():进行证书验证;allTrust:绕过证书验证
            PoolingHttpClientConnectionManager connectionManager = allTrust();
            try (CloseableHttpClient client = HttpClients.custom().setConnectionManager(connectionManager).build()) {
                HttpPost post = new HttpPost(url);
                //指定报文头
                post.setHeader("Context-Type", "application/json;charset=UTF-8");
                //设置entity
                StringEntity entity = new StringEntity(JSONObject.toJSONString(content), "UTF-8");
                entity.setContentType("application/json");
                post.setEntity(entity);
                //发送请求
                response = client.execute(post);
                log.info("response->:{}", response);
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    returnInfo = EntityUtils.toString(resEntity, "UTF-8");
                }
                EntityUtils.consume(resEntity);
                response.close();
                return returnInfo;
            } catch (IOException | ParseException e) {
                log.info("errorLogs->:{}", e);
                return returnInfo;
            }
    
        }
    
        /**
         * 绕过验证
         * @author xz
         */
        public static PoolingHttpClientConnectionManager allTrust() {
            SSLContext sslContext = null;
    
            PoolingHttpClientConnectionManager connectionManager = null;
            try {
                sslContext = SSLContext.getInstance("TLSv1.2");
                X509TrustManager trustManager = new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    
                    }
    
                    @Override
                    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    
                    }
    
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
                };
                sslContext.init(null, new TrustManager[]{trustManager}, null);
    
                //设置http和https对应处理socket链接工厂的对象
                Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.INSTANCE)
                        .register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
                        .build();
                connectionManager = new PoolingHttpClientConnectionManager(registry);
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                log.info("errorLogs->:{}", e);
            }
    
            return connectionManager;
        }
    
        /**
         * 进行证书验证
         * @author xz
         */
        public static PoolingHttpClientConnectionManager getTrust() {
            PoolingHttpClientConnectionManager connectionManager = null;
            try {
                CertificateFactory certificateFactory = CertificateFactory.getInstance("x.509");
                //证书路径
                ClassPathResource classPathResource = new ClassPathResource("xxxx.pem");
                Certificate certificate = certificateFactory.generateCertificate(classPathResource.getInputStream());
                //creat TrustStore
                KeyStore keyStore = KeyStore.getInstance("JKS");
                keyStore.load(null ,null);
                //Add certificate
                keyStore.setCertificateEntry("key",certificate);
                TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustManagerFactory.init(keyStore);
                //creatSSlContext
                SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
                sslContext.init(null,trustManagerFactory.getTrustManagers(),null);
                //设置http和https对应处理socket链接工厂的对象
                Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.INSTANCE)
                        .register("https", new SSLConnectionSocketFactory(sslContext))
                        .build();
                connectionManager = new PoolingHttpClientConnectionManager(registry);
            } catch (CertificateException | IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) {
                log.info("errorLogs->:{}", e);
            }
    
            return connectionManager;
        }
    
    }

三、测试类

  • 测试代码

    java 复制代码
    package com.xz.https;
    
    import com.alibaba.fastjson.JSONObject;
    
    /**
     * @author: xz
     * @since: 2024/1/11 22:17
     * @description:
     */
    public class HttpsUtilsTest {
        public static void main(String[] args) throws Exception {
            String url="https://xxx.com.cn:5678/gateway/user/service/getxxxx";
            UserReq userReq = new UserReq ();
            userReq .setName("张三");
            JSONObject parse = (JSONObject)JSONObject.parse(JSONObject.toJSONString(userReq));
            String result = HttpsUtil.post(url, parse);
            System.out.println("HttpClient---https请求:"+result);
        }
    }
  • 测试输出结果

相关推荐
Q_19284999067 分钟前
基于Spring Boot的个人健康管理系统
java·spring boot·后端
m0_748245171 小时前
Web第一次作业
java
小码的头发丝、1 小时前
Java进阶学习笔记|面向对象
java·笔记·学习
m0_548514771 小时前
前端Pako.js 压缩解压库 与 Java 的 zlib 压缩与解压 的互通实现
java·前端·javascript
坊钰1 小时前
【Java 数据结构】移除链表元素
java·开发语言·数据结构·学习·链表
chenziang12 小时前
leetcode hot100 LRU缓存
java·开发语言
会说法语的猪2 小时前
springboot实现图片上传、下载功能
java·spring boot·后端
码农老起2 小时前
IntelliJ IDEA 基本使用教程及Spring Boot项目搭建实战
java·ide·intellij-idea
m0_748239832 小时前
基于web的音乐网站(Java+SpringBoot+Mysql)
java·前端·spring boot