下面列出了怎么用org.apache.http.conn.ssl.SSLContexts的API类实例代码及写法,或者点击链接到github查看源代码。
public static CloseableHttpClient ceateSSLClient(File keyFile, String protocol, String password){
CloseableHttpClient httpclient = null;
try{
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(keyFile);
try {
keyStore.load(instream, password.toCharArray());
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray()).build();
String[] protocols = new String[] {protocol};
//ALLOW_ALL_HOSTNAME_VERIFIER 关闭host验证,允许和所有的host建立SSL通信
//BROWSER_COMPATIBLE_HOSTNAME_VERIFIER 和浏览器兼容的验证策略,即通配符能够匹配所有子域名
//STRICT_HOSTNAME_VERIFIER 严格匹配模式,hostname必须匹配第一个CN或者任何一个subject-alts
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,protocols,null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
}catch(Exception e){
e.printStackTrace();
}
return httpclient;
}
private SSLContext createSSLContext(final SSLContextService service)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
SSLContextBuilder builder = SSLContexts.custom();
final String trustFilename = service.getTrustStoreFile();
if (trustFilename != null) {
final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
truststore.load(in, service.getTrustStorePassword().toCharArray());
}
builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
}
final String keyFilename = service.getKeyStoreFile();
if (keyFilename != null) {
final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
keystore.load(in, service.getKeyStorePassword().toCharArray());
}
builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
}
builder = builder.useProtocol(service.getSslAlgorithm());
final SSLContext sslContext = builder.build();
return sslContext;
}
private void httpConfig() {
LOG.info("Setting up http Matrix Federation for id: " + userId);
SSLContext sslcontext;
try {
sslcontext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
CloseableHttpClient httpclient = HttpClients.custom()
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
.setSSLContext(sslcontext)
.build();
Unirest.setHttpClient(httpclient);
Unirest.setDefaultHeader("Content-Type","application/json");
}
private static RestTemplate createRestTemplate(String host, String username, String password, Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(host, 25555),
new UsernamePasswordCredentials(username, password));
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.useTLS()
.build();
SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
HttpClient httpClient = HttpClientBuilder.create()
.disableRedirectHandling()
.setDefaultCredentialsProvider(credentialsProvider)
.setSSLSocketFactory(connectionFactory)
.build();
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
restTemplate.getInterceptors().addAll(interceptors);
return restTemplate;
}
/**
* Creates an HTTP client that trusts all upstream servers and uses a localhost proxy on the specified port.
*/
private static CloseableHttpClient getNewHttpClient(int proxyPort) {
try {
// Trust all certs -- under no circumstances should this ever be used outside of testing
SSLContext sslcontext = SSLContexts.custom()
.useTLS()
.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
})
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setProxy(new HttpHost("127.0.0.1", proxyPort))
// disable decompressing content, since some tests want uncompressed content for testing purposes
.disableContentCompression()
.disableAutomaticRetries()
.build();
return httpclient;
} catch (Exception e) {
throw new RuntimeException("Unable to create new HTTP client", e);
}
}
/**
* Gets the trusted ssl context.
*
* @param trustStoreFile the trust store file
* @param trustStorePassword the trust store password
* @param trustStoreType the trust store type
* @return the trusted ssl context
*/
private static SSLContext getTrustedSslContext(final File trustStoreFile, final String trustStorePassword,
final String trustStoreType) {
try {
if (!trustStoreFile.exists() || !trustStoreFile.canRead()) {
throw new FileNotFoundException("Truststore file cannot be located at " + trustStoreFile.getCanonicalPath());
}
final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();
try (final FileInputStream casStream = new FileInputStream(trustStoreFile)) {
casTrustStore.load(casStream, trustStorePasswordCharArray);
}
final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
final X509KeyManager customKeyManager = getKeyManager("PKIX", casTrustStore, trustStorePasswordCharArray);
final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
final X509TrustManager customTrustManager = getTrustManager("PKIX", casTrustStore);
final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);
final KeyManager[] keyManagers = {
new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager))
};
final TrustManager[] trustManagers = {
new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager))
};
final SSLContext context = SSLContexts.custom().useSSL().build();
context.init(keyManagers, trustManagers, null);
return context;
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
private CloseableHttpClient getDefaultHttpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
new AllowAllHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
}
private CloseableHttpClient getDefaultHttpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
new AllowAllHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
}
/**
* 利用证书请求微信
*
* @param certPath 证书路径
* @param passwd 证书密码
* @param uri 请求地址
* @param entity 请求体xml内容
* @param encording 编码格式
* @throws Exception 异常
* @return 得到的结果
*/
public static String post(String certPath, String passwd, String uri, InputStreamEntity entity,
String encording) throws Exception {
String result = null;
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File(certPath));
try {
keyStore.load(instream, passwd.toCharArray());
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, passwd.toCharArray()).build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"},
null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
try {
HttpPost httpPost = new HttpPost(uri);
entity.setContentEncoding(encording);
httpPost.setEntity(entity);
CloseableHttpResponse httpResponse = httpclient.execute(httpPost);
result = consumeResponse(httpResponse, encording);
} finally {
httpclient.close();
}
return result;
}
private void init() throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File(config.getCertLocalPath()));//加载本地的证书进行https加密传输
try {
keyStore.load(instream,config.getCertPassword().toCharArray());//设置证书密码
} catch (Exception e) {
e.printStackTrace();
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, config.getCertPassword().toCharArray())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[]{"TLSv1"},
null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
//根据默认超时限制初始化requestConfig
requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
hasInit = true;
}
private void init() throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File(config.getCertLocalPath()));//加载本地的证书进行https加密传输
try {
keyStore.load(instream,config.getCertPassword().toCharArray());//设置证书密码
} catch (Exception e) {
e.printStackTrace();
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, config.getCertPassword().toCharArray())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[]{"TLSv1"},
null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
//根据默认超时限制初始化requestConfig
requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
hasInit = true;
}
/**
* Trust self-signed certificates on the rocketchat server url.
* @throws KeyManagementException
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
*/
public void trustSelfSignedCertificates()
throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
Unirest.setHttpClient(httpclient);
}
private SSLContext getSslContext() {
try {
// Build truststore
String trustStoreFile = getProperty("zeppelin.livy.ssl.trustStore");
String trustStorePassword = getProperty("zeppelin.livy.ssl.trustStorePassword");
String trustStoreType = getProperty("zeppelin.livy.ssl.trustStoreType",
KeyStore.getDefaultType());
if (StringUtils.isBlank(trustStoreFile)) {
throw new RuntimeException("No zeppelin.livy.ssl.trustStore specified for livy ssl");
}
if (StringUtils.isBlank(trustStorePassword)) {
throw new RuntimeException("No zeppelin.livy.ssl.trustStorePassword specified " +
"for livy ssl");
}
KeyStore trustStore = getStore(trustStoreFile, trustStoreType, trustStorePassword);
SSLContextBuilder builder = SSLContexts.custom();
builder.loadTrustMaterial(trustStore);
// Build keystore
String keyStoreFile = getProperty("zeppelin.livy.ssl.keyStore");
String keyStorePassword = getProperty("zeppelin.livy.ssl.keyStorePassword");
String keyPassword = getProperty("zeppelin.livy.ssl.keyPassword", keyStorePassword);
String keyStoreType = getProperty("zeppelin.livy.ssl.keyStoreType",
KeyStore.getDefaultType());
if (StringUtils.isNotBlank(keyStoreFile)) {
KeyStore keyStore = getStore(keyStoreFile, keyStoreType, keyStorePassword);
builder.loadKeyMaterial(keyStore, keyPassword.toCharArray()).useTLS();
}
return builder.build();
} catch (Exception e) {
throw new RuntimeException("Failed to create SSL Context", e);
}
}
private HttpClient createHttpClient(ConnectionConfig config) {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(config.getConnectionTimeoutMs())
.setSocketTimeout(config.getSocketTimeoutMs())
.build();
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
registryBuilder.register("http", new PlainConnectionSocketFactory());
if (config.isHttpsEnabled()) {
SSLContext sslContext = SSLContexts.createSystemDefault();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registryBuilder.register("https", sslsf);
}
connectionManager = new PoolingHttpClientConnectionManager(registryBuilder.build());
connectionManager.setDefaultMaxPerRoute(config.getMaxConnection());
connectionManager.setMaxTotal(config.getMaxConnection());
HttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.setRetryHandler(new DefaultHttpRequestRetryHandler(3, false))
.build();
return httpClient;
}
private SSLContext createSslContext(
final String algorithm,
final KeyStore keystore,
final String keyPassword,
final KeyStore truststore,
final SecureRandom random)
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
return SSLContexts.custom()
.useProtocol(algorithm)
.setSecureRandom(random)
.loadKeyMaterial(keystore, keyPassword != null ? keyPassword.toCharArray() : null)
.loadTrustMaterial(truststore)
.build();
}
public HttpUtility(UserPreferences userPrefs, boolean useAuth, int maxRetries, double retryDelayFactor) {
this.maxRetries = maxRetries;
this.retryDelayFactor = retryDelayFactor;
HttpClientBuilder clientBuilder = HttpClients.custom();
if (useAuth) {
authHeader = getAuthHeader(userPrefs.getUsername(), userPrefs.getPassword());
appToken = userPrefs.getConnectionInfo().getToken();
}
authRequired = useAuth;
if(userPrefs != null) {
String proxyHost = userPrefs.getProxyHost();
String proxyPort = userPrefs.getProxyPort();
if (canUse(proxyHost) && canUse(proxyPort)) {
HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort));
proxyConfig = RequestConfig.custom().setProxy(proxy).build();
if (canUse(userPrefs.getProxyUsername()) && canUse(userPrefs.getProxyPassword())) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(proxyHost, Integer.valueOf(proxyPort)),
new UsernamePasswordCredentials(userPrefs.getProxyUsername(), userPrefs.getProxyPassword()));
clientBuilder.setDefaultCredentialsProvider(credsProvider);
}
}
}
RequestConfig requestConfig = RequestConfig.custom().
setConnectTimeout(15000). // 15s
setSocketTimeout(60000). // 1m
build();
SSLContext sslContext;
try {
sslContext = SSLContexts.custom().useTLS().build();
} catch (NoSuchAlgorithmException|KeyManagementException e) {
// there’s no way for the client to recover,
// so a checked exception is not necessary
throw new RuntimeException(e);
}
SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(
sslContext,
new String[] { "TLSv1.1", "TLSv1.2" },
null,
BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
);
httpClient = HttpClients.custom().
setSSLSocketFactory(factory).
setRetryHandler(datasyncDefaultHandler).
setKeepAliveStrategy(datasyncDefaultKeepAliveStrategy).
setDefaultRequestConfig(requestConfig).
build();
}
/**
* 接入微信支付退款和微信红包接口,需要使用证书提交请求,故编写此方法
* <ul>
* <li>亲测:post()提交请求时,微信服务器会报告异常:“java.lang.RuntimeException: 证书出错,请登录微信支付商户平台下载证书”</li>
* <li>另外也试过“java InstallCert api.mch.weixin.qq.com”,仍然会报告:“PKIX path building failed”</li>
* <li>所以:要使用postWithP12(),它内部会调用该方法实现证书的发送,目前该方法支持.p12文件</li>
* <li>微信提供了通过证书提交请求的demo:https://pay.weixin.qq.com/wiki/doc/api/download/cert.zip,下面是实际的代码</li>
* <li>
* package httpstest;
* import java.io.BufferedReader;
* import java.io.File;
* import java.io.FileInputStream;
* import java.io.InputStreamReader;
* import java.security.KeyStore;
* import javax.net.ssl.SSLContext;
* 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.SSLContexts;
* 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.util.EntityUtils;
* //This example demonstrates how to create secure connections with a custom SSLcontext.
* public class ClientCustomSSL {
* public final static void main(String[] args) throws Exception {
* KeyStore keyStore = KeyStore.getInstance("PKCS12");
* FileInputStream instream = new FileInputStream(new File("D:/10016225.p12"));
* try {
* keyStore.load(instream, "10016225".toCharArray());
* } finally {
* instream.close();
* }
* // Trust own CA and all self-signed certs
* SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "10016225".toCharArray()).build();
* // Allow TLSv1 protocol only
* SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
* CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
* try {
* HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");
* System.out.println("executing request" + httpget.getRequestLine());
* CloseableHttpResponse response = httpclient.execute(httpget);
* try {
* HttpEntity entity = response.getEntity();
* System.out.println("----------------------------------------");
* System.out.println(response.getStatusLine());
* if (entity != null) {
* System.out.println("Response content length: " + entity.getContentLength());
* BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
* String text;
* while ((text = bufferedReader.readLine()) != null) {
* System.out.println(text);
* }
* }
* EntityUtils.consume(entity);
* } finally {
* response.close();
* }
* } finally {
* httpclient.close();
* }
* }
* }
* </li>
* </ul>
* @param filepath 证书文件路径
* @param password 证书密码
*/
private static HttpClient addTLSSupport(HttpClient httpClient, String filepath, String password) throws Exception {
//KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
KeyStore keyStore = KeyStore.getInstance("PKCS12");
try(FileInputStream fis = new FileInputStream(new File(filepath))){
keyStore.load(fis, password.toCharArray());
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray()).build();
//// Allow TLSv1 protocol only
//SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
SSLSocketFactory socketFactory = new SSLSocketFactory(sslcontext);
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
return httpClient;
}