设置https请求忽略安全证书

前两天要调用第三方的接口遇到了安全证书的问题,找了各种方法下面贴一下自己汇总的解决办法:

第一个写法(这个写法是最简单的,亲测有效,但是这个写法用到了jdk1.8的lambda表达式,1.8之前的版本就不支持):

private static CloseableHttpClient httpClient;
	//jdk1.8用此代码 
    static {
        try {
            SSLContext sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
            RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();
            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

然后直接调用httpClient就行了

第二个方法(我用的版本就是1.7的 所以用了这个办法):

private static CloseableHttpClient httpClient;
static {
		try {
			HostnameVerifier hv = new HostnameVerifier() {
				@Override
				public boolean verify(String hostname, SSLSession session) {
					return true;
				}
		    };
		    javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
	    	javax.net.ssl.TrustManager tm = new miTM();
	    	trustAllCerts[0] = tm;
	    	javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
	    			.getInstance("SSL");
	    	sc.init(null, trustAllCerts, null);
	    	javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
	    			.getSocketFactory());
			RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();
			httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sc).setSSLHostnameVerifier(hv).build();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 
    static class miTM implements javax.net.ssl.TrustManager,
    javax.net.ssl.X509TrustManager {
    	public java.security.cert.X509Certificate[] getAcceptedIssuers() {
    		return null;
    	}
    	
    	public boolean isServerTrusted(
    			java.security.cert.X509Certificate[] certs) {
    		return true;
    	}
    	
    	public boolean isClientTrusted(
    			java.security.cert.X509Certificate[] certs) {
    		return true;
    	}
    	
    	public void checkServerTrusted(
    			java.security.cert.X509Certificate[] certs, String authType)
    					throws java.security.cert.CertificateException {
    		return;
    	}
    	
    	public void checkClientTrusted(
    			java.security.cert.X509Certificate[] certs, String authType)
    					throws java.security.cert.CertificateException {
    		return;
    	}
    }

也是直接调用httpClient就行了,亲测有效。

你可能感兴趣的:(java笔记)