Apache HTTPClient 忽略证书_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Apache HTTPClient 忽略证书

Apache HTTPClient 忽略证书

 2019/1/25 15:32:48  tomhat  程序员俱乐部  我要评论(0)
  • 摘要:/***httpclient4.5.2版*忽略服务器证书,采用信任机制*@return*/publicstaticHttpClientConnectionManagerinit(){try{SSLContextsslContext=SSLContexts.custom().loadTrustMaterial(null,newTrustStrategy(){@OverridepublicbooleanisTrusted(X509Certificate[]arg0,Stringarg1
  • 标签:client Apache HTTP
class="java" name="code">
/**
 * 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();
	}
}
发表评论
用户名: 匿名