java中HttpClient发送https请求忽略SSL证书

前言:搜了好多篇博文,奇奇怪怪的方式都有----导的包不说清楚的、自己封装一大堆代码的还不能用的。。。(狗子,你说你何必写出来呢?)
试了几种,都没用,最后发现这种方式有用,而且代码量少,,,为维护世界和平,copy过来润润色,nice(自信的顺一顺仅有的几根头发)

亲测这种方式是有用的,你先试试看,没用的话,别打我,我打不过你。。。。。
1、导入HttpClient的pom依赖(版本4.4.1)
<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpcoreartifactId>
    <version>4.4.1version>
dependency>
<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpclientartifactId>
    <version>4.4.1version>
dependency>
<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpcore-nioartifactId>
    <version>4.4.1version>
dependency>
<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpmimeartifactId>
    <version>4.4.1version>
dependency>
2、忽略SSL证书,发送https请求示例
(1)类中的核心依赖:
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
(2)核心代码(此处以post请求位例):
//配置,发送https请求时,忽略ssl证书认证(否则会报错没有证书)
SSLContext sslContext = null;
try {
    sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            return true;
        }
    }).build();
} catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
} catch (KeyManagementException e) {
    e.printStackTrace();
} catch (KeyStoreException e) {
    e.printStackTrace();
}

//创建httpClient
CloseableHttpClient client = HttpClients.custom().setSslcontext(sslContext).
        setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        
//创建 POST请求对象
HttpPost post = new HttpPost("https://" + URL_PATH);
//请求参数设置
JSONObject param = new JSONObject(true);
param.put("name", "李狗蛋");
param.put("department", "狗子部");
String jsonParam = param.toString();
post.setEntity(new StringEntity(jsonParam, "UTF-8"));

//请求头设置
post.addHeader("Content-Type", "application/json; charset=utf-8");
post.addHeader("Host", URL_HOST);

//请求超时时间设置
post.setConfig(RequestConfig.custom()
// 连接超时时间
.setConnectTimeout(5000)
// 请求超时时间
.setConnectionRequestTimeout(5000)
// Socket读取超时时间
.setSocketTimeout(5000)
// 是否允许重定向
.setRedirectsEnabled(false)
.build());

//发送请求
CloseableHttpResponse response = null;
try {
    response = client.execute(post);
} catch (IOException e) {
    e.printStackTrace();
    log.error("请求发送失败");
    return  responseDto;
}

//处理请求结果 response 

你可能感兴趣的:(java)