在Java11中,配置也类似这个链接中:http://www.cjavapy.com/article/52/,具体代码如下,
package Demo; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.time.Duration; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public class httpclientdemo { public static void main(String[] args) throws NoSuchAlgorithmException, Exception, InterruptedException { TrustManager[] trustAllCertificates = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; // Not relevant. } @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { // TODO Auto-generated method stub } } }; //HostnameVerifier trustAllHostnames = new HostnameVerifier() { // @Override // public boolean verify(String hostname, SSLSession session) { // return true; // Just allow them all. // } }; var timeoutInSeconds = 60; SSLParameters sslParams = new SSLParameters(); sslParams.setEndpointIdentificationAlgorithm(""); SSLContext sc = SSLContext.getInstance("SSL"); System.setProperty("jdk.internal.httpclient.disableHostnameVerification","true");//取消主机名验证 sc.init(null, trustAllCertificates, new SecureRandom()); HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofMillis(timeoutInSeconds * 1000)) .sslContext(sc) .sslParameters(sslParams) .build(); HttpRequest requestBuilder = HttpRequest.newBuilder().uri(URI.create("https://www.example.com/getSomething")) .GET().build(); HttpResponse<String> result = httpClient.send(requestBuilder, HttpResponse.BodyHandlers.ofString()); //发送请求 } }