Fabrizio Russo Ignorare il certificato in chiamate HTTPS


2017/01/07   Ignorare il certificato in chiamate HTTPS

Alcune volte è necessario effettuare una connessione HTTPS ignorando la validita' del certificato SSL, ad esempio quando il certificato e' self-signed e non si ha la possibilita' di importare il certificato nel keystore della JVM.

In questo caso, utilizzando le librerie org.apache.http di può utilizzare il seguente metodo getHttpClient per ottenere un client per le connessioni in grado di ignorare la validta' del certificato.


private HttpClient getHttpClient() throws Exception {
	SSLContextBuilder builder = SSLContexts.custom();
	builder.loadTrustMaterial(null, new TrustStrategy() {
		@Override
		public boolean isTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			return true;
		}
	});

	SSLContext sslContext = builder.build();
	SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
		sslContext, new X509HostnameVerifier() {
			@Override
			public void verify(String host, SSLSocket ssl) 
				throws java.io.IOException {}

			@Override
			public void verify(String host, X509Certificate cert) 
				throws SSLException {} 

			@Override
			public void verify(String host, String[] cns, String[] subjectAlts) 
				throws SSLException {}

			@Override
			public boolean verify(String s, SSLSession sslSession) {
				return true;
			}
		});

	Registry socketFactoryRegistry = 
		RegistryBuilder. create()
		.register("https", sslsf).build();

	PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
	CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
	return httpClient;
}

 

Successivamente e' possibile utilizzare il client ottenuto per creare connessioni in POST o in GET

Esempio di chiamata in POST


HttpClient httpClient = getHttpClient();
		
HttpEntity entity = MultipartEntityBuilder
	    .create()
	    .addTextBody(paramName, paramValue)
	    .build();

HttpPost httpPost = new HttpPost(endPoint);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity result = response.getEntity();

Esempio di chiamata in GET


HttpClient httpClient = getHttpClient();

StringBuilder queryString = new StringBuilder("?");
queryString.append("param1=" + paramValue1);
queryString.append("¶m2=" + paramValue2);



String url = endPoint + queryString.toString();
HttpGet httpGet= new HttpGet(url);
	
HttpResponse response = httpClient.execute(httpGet);
BufferedReader rd = new BufferedReader
	  (new InputStreamReader(response.getEntity().getContent()));
	
StringBuilder textResult = new StringBuilder("");
String line = "";
while ((line = rd.readLine()) != null) {
	textResult.append(line);
}