我的tomcat服务器设置为使用自签名(因此,不受信任)证书使用SSL。有时也需要允许不安全的HTTPS连接,例如在一些与其它站点一起使用的Web爬行应用程序中。我在以前的HttpsURLConnection API中,之前的解决方案:设置URLConnection允许不安全Https连接,最近被JDK 11中的有了新HttpClient API。下面分享一下设置方法。

在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()); //发送请求
	}
}