目录
一、引入依赖包
-
引入相关依赖包
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工具类代码
javapackage 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; } }
三、测试类
-
测试代码
javapackage 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); } }
-
测试输出结果