Apache Http Client 4.1: Creare una connessione https validando tutti i certificati

Questo pezzo di codice crea una connessione https considerando validi tutti i certificati che arrivano dal server:

HttpClient httpclient = new DefaultHttpClient();
 
// creo un array di TrustManager per considerare tutti i certificati server validi		
X509TrustManager tm = new X509TrustManager() {
	public java.security.cert.X509Certificate[] getAcceptedIssuers() {
		return null;
	}
	public void checkClientTrusted(
	java.security.cert.X509Certificate[] certs, String authType) {
	}
	public void checkServerTrusted(
	java.security.cert.X509Certificate[] certs, String authType) {
	}
};    	
try {
	// Creo il contesto SSL utilizzando i trust manager creati			
	SSLContext ctx = SSLContext.getInstance("TLS");
	ctx.init(null, new TrustManager[]{tm}, null);
 
	// Creo la connessione https
	SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);			
	ClientConnectionManager ccm = httpclient.getConnectionManager();
	SchemeRegistry sr = ccm.getSchemeRegistry();
	sr.register(new Scheme("https", 443, ssf));
	httpclient = new DefaultHttpClient(ccm, httpclient.getParams());
 
} catch (NoSuchAlgorithmException e) {
	e.printStackTrace();		
} catch (KeyManagementException e) {
	e.printStackTrace();		
}
 
try {
	// Ora ad esempio eseguiamo una post:
	HttpPost post = new HttpPost("https://unbellinkhttpsconunbelcertificato.com");
	HttpResponse response = httpclient.execute(post);		
} catch (UnsupportedEncodingException e) {
	repres.errorMessage = e.getMessage();
} catch (ClientProtocolException e) {
	repres.errorMessage = e.getMessage();
} catch (ParseException e) {
	repres.errorMessage = e.getMessage();
} catch (IOException e) {
	repres.errorMessage = e.getMessage();
}

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>