springboot加载使用证书的ssl然后HttpClient请求

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.SecureRandom;


// 证书
char[] password = config.getMchID().toCharArray();
InputStream certStream = config.getCertStream();
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(certStream, password);

// 实例化密钥库 & 初始化密钥工厂
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, password);

// 创建 SSLContext
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());

SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
        sslContext,
        new String[]{
    
    "TLSv1"},
        null,
        new DefaultHostnameVerifier());

BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(
        RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslConnectionSocketFactory)
                .build(),
        null,
        null,
        null
);

HttpClient httpClient = HttpClientBuilder.create()
    .setConnectionManager(connManager)
    .build();

String url = "https://" + domain + urlSuffix;
HttpPost httpPost = new HttpPost(url);

RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
httpPost.setConfig(requestConfig);

StringEntity postEntity = new StringEntity(data, "UTF-8");
httpPost.addHeader("Content-Type", "text/xml");
httpPost.addHeader("User-Agent", USER_AGENT + " " + config.getMchID());
httpPost.setEntity(postEntity);

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
EntityUtils.toString(httpEntity, "UTF-8");
public static SSLConnectionSocketFactory initCert(String certPath,String mid) throws Exception {
    
    
    FileInputStream instream = null;
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    instream = new FileInputStream(new File(certPath));
    keyStore.load(instream, mid.toCharArray());

    if (null != instream) {
    
    
        instream.close();
    }
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,mid.toCharArray()).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{
    
    "TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    return sslsf;
}

public static CloseableHttpResponse httpPostBy(String urlAddress,String outputEntity,String certPath,String mid, boolean isLoadCert)throws Exception {
    
    
		HttpPost httpPost = new HttpPost(urlAddress);
        // 得指明使用UTF-8编码,否则到API服务器XML的中文不能被成功识别
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.setEntity(new StringEntity(outputEntity, "UTF-8"));
        if (isLoadCert) {
    
    
            // 加载含有证书的http请求
            return HttpClients.custom().setSSLSocketFactory(CertUtil.initCert(certPath,mid)).build().execute(httpPost);
        } else {
    
    
            return HttpClients.custom().build().execute(httpPost);
        }
	}

猜你喜欢

转载自blog.csdn.net/c5113620/article/details/104659870