最近在做微信退款,需要加载本地证书,先上代码
public static String postXmlWithKey(String url, String xml, String cerPath, String mchId) throws Exception {
InputStream in = new FileInputStream(new File(cerPath));
KeyStore keyStore = KeyStore.getInstance("PKCS12");
try {
keyStore.load(in, mchId.toCharArray());
} finally {
in.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, mchId.toCharArray())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[]{"TLSv1"},
null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient client = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
StringBuilder sb = new StringBuilder();
HttpPost httpPost = new HttpPost(url);
HttpEntity entity = null;
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
try {
StringEntity payload = new StringEntity(xml, "UTF-8");
httpPost.setEntity(payload);
HttpResponse response = client.execute(httpPost);
entity = response.getEntity();
String text;
if (entity != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
while ((text = bufferedReader.readLine()) != null) {
sb.append(text);
}
}
} catch (Exception e) {
logger.error("与[" + url + "]通信过程中发生异常,堆栈信息如下", e.getCause());
} finally {
try {
EntityUtils.consume(entity);
} catch (IOException ex) {
ex.printStackTrace();
logger.error("net io exception");
}
}
return sb.toString();
}
然后分析这段代码
//封装操作
SSLContext sslcontext = SSLContexts
.custom()
.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) //加载本地信任证书 信任自签名策略
.loadKeyMaterial(clientStore, "123456".toCharArray()) //加载本地证书
.build(); //构造
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext); //制造一个socket
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
作者:送你一碗大麦茶
链接:https://www.jianshu.com/p/2ad576f5a4d6
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。