欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Apache HTTPClient 忽略证书

程序员文章站 2022-03-04 18:25:10
...
/**
 * httpclient4.5.2版
 * 忽略服务器证书,采用信任机制
 * @return
 */
public static HttpClientConnectionManager init(){
	try {
		SSLContext sslContext  = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
			@Override
			public boolean isTrusted(X509Certificate[] arg0, String arg1)
					throws CertificateException {
				return true;
			}
		}).build();
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslContext, new String[] { "TLSv1" }, null,
				SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		Registry registry = RegistryBuilder
				. create()
				.register("http", PlainConnectionSocketFactory.INSTANCE)
				.register("https", sslsf).build();
		return new PoolingHttpClientConnectionManager(registry);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}


/**
 * javax.net.ssl
 * 忽略服务器证书,采用信任机制
 */
private static void disableSslVerification() {
	try {
		// Create a trust manager that does not validate certificate chains
		TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}

			public void checkClientTrusted(X509Certificate[] certs, String authType) {
			}

			public void checkServerTrusted(X509Certificate[] certs, String authType) {
			}
		}
		};

		// Install the all-trusting trust manager
		SSLContext sc = SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, new java.security.SecureRandom());
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

		// Create all-trusting host name verifier
		HostnameVerifier allHostsValid = new HostnameVerifier() {
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		};

		// Install the all-trusting host verifier
		HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
	} catch (KeyManagementException e) {
		e.printStackTrace();
	}
}
相关标签: java https