Last active
December 18, 2015 12:09
-
-
Save zjor/5781241 to your computer and use it in GitHub Desktop.
Convenient class for building SSL careless multithreaded Apache httpclient. Compatible with version 4.2.3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import lombok.extern.slf4j.Slf4j; | |
import org.apache.http.conn.ClientConnectionManager; | |
import org.apache.http.conn.scheme.Scheme; | |
import org.apache.http.conn.scheme.SchemeRegistry; | |
import org.apache.http.conn.ssl.SSLSocketFactory; | |
import org.apache.http.impl.client.AbstractHttpClient; | |
import org.apache.http.impl.client.DefaultHttpClient; | |
import org.apache.http.impl.conn.PoolingClientConnectionManager; | |
import javax.net.ssl.SSLContext; | |
import javax.net.ssl.TrustManager; | |
import javax.net.ssl.X509TrustManager; | |
import java.security.cert.CertificateException; | |
import java.security.cert.X509Certificate; | |
/** | |
* @author: Sergey Royz | |
*/ | |
@Slf4j | |
public class HttpClientBuilder { | |
private AbstractHttpClient baseHttpClient; | |
public HttpClientBuilder() { | |
baseHttpClient = new DefaultHttpClient(); | |
} | |
public AbstractHttpClient get() { | |
return baseHttpClient; | |
} | |
public HttpClientBuilder withTrustAllManager() { | |
try { | |
SSLContext ctx = SSLContext.getInstance("TLS"); | |
ctx.init(null, new TrustManager[]{ new TrustAllManager() }, null); | |
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); | |
ClientConnectionManager ccm = baseHttpClient.getConnectionManager(); | |
SchemeRegistry sr = ccm.getSchemeRegistry(); | |
sr.register(new Scheme("https", 443, ssf)); | |
baseHttpClient = new DefaultHttpClient(ccm, baseHttpClient.getParams()); | |
} catch (Exception ex) { | |
log.error("Unable to create client withTrustAllManager", ex); | |
} | |
return this; | |
} | |
public HttpClientBuilder withMultiThreadedEnvironment() { | |
SchemeRegistry sr = baseHttpClient.getConnectionManager().getSchemeRegistry(); | |
ClientConnectionManager ccm = new PoolingClientConnectionManager(sr); | |
baseHttpClient = new DefaultHttpClient(ccm, baseHttpClient.getParams()); | |
return this; | |
} | |
static class TrustAllManager implements X509TrustManager { | |
@Override | |
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { | |
} | |
@Override | |
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { | |
} | |
@Override | |
public X509Certificate[] getAcceptedIssuers() { | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment