Created
September 6, 2017 07:58
-
-
Save zhoulifu/21cc2441266f660f59862e98d816ce63 to your computer and use it in GitHub Desktop.
HttpClient demo with ssl
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 java.io.File; | |
import java.security.cert.CertificateException; | |
import java.security.cert.X509Certificate; | |
import org.apache.http.HttpEntity; | |
import org.apache.http.client.methods.CloseableHttpResponse; | |
import org.apache.http.client.methods.HttpGet; | |
import org.apache.http.conn.ssl.DefaultHostnameVerifier; | |
import org.apache.http.conn.ssl.SSLConnectionSocketFactory; | |
import org.apache.http.impl.client.CloseableHttpClient; | |
import org.apache.http.impl.client.HttpClients; | |
import org.apache.http.ssl.SSLContextBuilder; | |
import org.apache.http.ssl.SSLContexts; | |
import org.apache.http.ssl.TrustStrategy; | |
import org.apache.http.util.EntityUtils; | |
class NegativeTrustStrategy implements TrustStrategy { | |
public boolean isTrusted(X509Certificate[] chain, String authType) | |
throws CertificateException { | |
return false; // Only trust the specific keystore file | |
} | |
} | |
public class HttpClientWithSSL { | |
private static final String[] SUPPORTED_PROTOCOLS = new String[]{"TLSv1"}; | |
public static void main(String[] args) throws Exception { | |
SSLContextBuilder builder = SSLContexts.custom(); | |
builder.loadTrustMaterial(new File("client.jks"), "psw".toCharArray(), | |
new NegativeTrustStrategy()); | |
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), | |
SUPPORTED_PROTOCOLS, | |
null, | |
new DefaultHostnameVerifier()); | |
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf) | |
.build(); | |
try { | |
HttpGet httpget = new HttpGet("https://localhost"); | |
System.out.println("Executing request " + httpget.getRequestLine()); | |
CloseableHttpResponse response = httpclient.execute(httpget); | |
try { | |
HttpEntity entity = response.getEntity(); | |
System.out.println("----------------------------------------"); | |
System.out.println(EntityUtils.toString(entity)); | |
} finally { | |
response.close(); | |
} | |
} finally { | |
httpclient.close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment