PS:禁止拷贝形式转载,转载请以URL形式
1.简介
java11 更新了更新了访问http 的库,网上忽略https 都是基于java8 ,根据网上基于java8忽略HTTPS方式然后翻阅源码记录基于11环境下怎么忽略HTTPS。
2.参考
https://blog.csdn.net/shumeng_xiaoyan/article/details/76503601
3.代码
import javax.net.ssl.*;
import java.io.IOException;
import java.net.Socket;
import java.net.URI;
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.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.time.Duration;
/**
* @ClassName
* @Description
* @Author dyf
* @Date 2022/3/17
* @Version 1.0
*/
public class Test {
public static void main(String[] args) throws IOException, InterruptedException, KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException {
SSLContext sslcontext = SSLContext.getInstance("SSL","SunJSSE");
//X509ExtendedTrustManager:忽略证书验证,忽略主机名检查
sslcontext.init(null, new TrustManager[]{new X509ExtendedTrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
}
}}, new java.security.SecureRandom());
HttpClient httpClient= HttpClient.newBuilder().sslContext(sslcontext).build();
String uri = "https://localhost:8443/xxxxx";
HttpRequest.Builder reBuilder = HttpRequest.newBuilder();
HttpRequest request = reBuilder
.header("Content-Type", "application/json")
//http 协议版本
.version(HttpClient.Version.HTTP_2)
//url 地址
.uri(URI.create(uri))
//超时时间
.timeout(Duration.ofMillis(3000))
.GET().build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
String rltString = response.body();
System.out.println(rltString);
}
}