spring boot配置RestTemplate发送https请求

 

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.CertificateException;

@Configuration
public class CustomRestTemplateConfig {

    @Value("${params.pfxKey}")
    private String  pfxKey;

    @Bean
    public RestTemplate customRestTemplate(RestTemplateBuilder restTemplateBuilder) {
        // 加载PFX文件到密钥存储
        KeyStore keyStore;
        try {
            keyStore = KeyStore.getInstance("PKCS12");
            InputStream inputStream = getClass().getClassLoader().getResourceAsStream("certificate/testISSUE.pfx");
            keyStore.load(inputStream, pfxKey.toCharArray());
        } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
            throw new RuntimeException("Failed to load PFX file into KeyStore.", e);
        }

        // 创建SSL上下文并初始化
        SSLContext sslContext;
        try {
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, pfxKey.toCharArray());
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
        } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
            throw new RuntimeException("Failed to initialize SSLContext.", e);
        }

        // 创建自定义的RestTemplate实例
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLContext(sslContext)
                .build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        RestTemplate restTemplate = restTemplateBuilder.requestFactory(() -> requestFactory).build();

        // 设置字符编码为UTF-8
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        stringConverter.setWriteAcceptCharset(false);
        restTemplate.getMessageConverters().removeIf(converter -> converter instanceof StringHttpMessageConverter);
        restTemplate.getMessageConverters().add(0, stringConverter);

        return restTemplate;
    }
}

  

posted @ 2023-11-16 10:17  非帆丶  阅读(557)  评论(0编辑  收藏  举报