httpclient 访问https

package WHTR.Common.Utility.HttpClient;


import java.io.File;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


import org.apache.http.client.HttpClient;
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.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


//用于进行Https请求的HttpClient
@SuppressWarnings("deprecation")
public class SSLClient extends DefaultHttpClient {
private static HttpClientBuilder httpClientBulider;

private static Logger logger = LoggerFactory.getLogger(SSLClient.class);




public SSLClient(String keyStorePath, String keyStorePassword, String trustStorePath, String trustStorePassword) {
if (httpClientBulider == null) {


try {
logger.info("准备创建SSLClient");
SSLContext context = SSLContexts.custom()
.loadKeyMaterial(new File(keyStorePath), keyStorePassword.toCharArray(),
keyStorePassword.toCharArray())
.loadTrustMaterial(new File(trustStorePath), trustStorePassword.toCharArray()).build();
SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(context, new String[] { "TLSv1.2" },
null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
httpClientBulider = HttpClients.custom().setSSLSocketFactory(sf);
} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException
| UnrecoverableKeyException | KeyManagementException e) {
//e.printStackTrace();
logger.error("SSLClient 创建失败",e);
}


}
}


public HttpClient getSSLHttpClient() {
return httpClientBulider.build();
}
}

你可能感兴趣的:(https)