RestTemplate HttpClient 加载 SSL/PKCS12/微信API证书

本文介绍了如何在Spring的RestTemplate和Apache HttpClient中配置并加载SSL证书,特别是PKCS12格式的证书,以及针对微信API的证书处理方法。涉及到的库版本为spring-web:5.1.8.RELEASE和httpclient:4.5.9。

版本:org.springframework:spring-web:5.1.8.RELEASE、org.apache.httpcomponents:httpclient:4.5.9

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

@Bean
public RestTemplate restTemplate(@Value("${weixin.key.file}") String keyFile, @Value("${weixin.key.password}") String keyPassword) {
    InputStream keyStream = getClass().getResourceAsStream(keyFile);
    KeyStore keyStore;
    try {
        keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(keyStream, keyPassword.toCharArray());
    } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    SSLContext sslContext;
    try {
        sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, keyPassword.toCharArray()).build();
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | UnrecoverableKeyException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
    HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    return new RestTemplate(httpRequestFactory);
}

(完)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值