java学习之HttpClient忽略安全证书(SSLContext)

1.我们在写https请求时候,经常会遇见安全证书(SSL)验证失败的情况,如下图。

 上图异常就是因为SSL验证失败导致的,常规的做法是忽略证书认证。方法如下:

第一步:需要重写认证的证书类 X509ExtendedTrustManager。

第二步:创建SSLContext对象。

第三步:将SSLContext对象设置到HttpClient中。

下面是完整的代码示例,亲测有效.

package org.example;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509ExtendedTrustManager;
import java.io.IOException;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


public class Main {

private static final TrustManager DUMMY_TRUST_MANAGER = new X509ExtendedTrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {

}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {

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

}
};

public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException, NoSuchAlgorithmException, KeyManagementException {
String url = "https://my.dream.bet/mock/bulk/users/restrictions?code=DW001,DW002&fromDate=20240101";
/** 创建SSLContext*/
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{DUMMY_TRUST_MANAGER}, new SecureRandom());
/** 将HSSLContext设置到HttpClient*/
HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();
HttpRequest request = HttpRequest.newBuilder()
.header("accept", "text/csv")
.header("X-API-KEY", "bYLhk7gqDb3RmT9Ahchen1ucqyhes5jpac8lA5Lf")
.uri(new URI(url)).build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
posted @ 2024-09-11 16:15  狗狗听话  阅读(270)  评论(0编辑  收藏  举报