RestTemplate客户端调用https接口设置ssl证书

        该文是演示如何给resttemplate客户端配置ssl证书来进行https接口调用。

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.KeyManagerFactory;

public class RestTemplateWithCertificate {
    public static void main(String[] args) throws Exception {
        // 加载证书
        Resource keyStoreResource = new ClassPathResource("client_keystore.jks");
        InputStream keyStoreInputStream = keyStoreResource.getInputStream();

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(keyStoreInputStream, "keystore_password".toCharArray());

        // 创建SSL上下文
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "keystore_password".toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());

        // 创建RestTemplate
        RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory() {
            @Override
            protected void prepareConnection(java.net.HttpURLConnection connection, String httpMethod) {
                if (connection instanceof javax.net.ssl.HttpsURLConnection) {
                    ((javax.net.ssl.HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
                }
            }
        });

        // 发送HTTPS请求
        String url = "https://example.com/api";
        String result = restTemplate.getForObject(url, String.class);
        System.out.println(result);
    }
}

其中 client_keystore.jks, keystore_password 和url 根据项目实现情况替换

### 忽略SSL证书验证的解决方案 在Spring Boot中调用HTTPS接口时,如果需要忽略SSL证书验证,可以通过自定义`RestTemplate`来实现。以下是详细的实现方法: #### 1. 配置类实现 通过创建一个配置类来生成`RestTemplate`实例,并设置忽略SSL证书验证的功能。 ```java import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory) { return new RestTemplate(factory); } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory() throws NoSuchAlgorithmException, KeyManagementException { TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) {} public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); CloseableHttpClient httpClient = HttpClients.custom() .setSSLContext(sslContext) .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setHttpClient(httpClient); return factory; } } ``` #### 2. 实现细节说明 - **TrustManager**:通过实现`X509TrustManager`接口并重写相关方法,可以跳过对服务器证书的信任检查[^2]。 - **SSLContext**:初始化`SSLContext`对象时,使用自定义的`TrustManager`以忽略SSL证书验证。 - **CloseableHttpClient**:基于`HttpClients`构建自定义的HTTP客户端,并设置`SSLContext`和主机名验证器[^3]。 - **Host Name Verifier**:通过`NoopHostnameVerifier`禁用主机名验证,确保即使证书中的主机名不匹配也能继续请求。 #### 3. 使用示例 以下是如何使用上述配置的`RestTemplate`进行HTTPS请求的示例代码: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class MyService { @Autowired private RestTemplate restTemplate; public String callSecureEndpoint(String url) { return restTemplate.getForObject(url, String.class); } } ``` ### 注意事项 - 忽略SSL证书验证会降低安全性,仅应在开发或测试环境中使用。生产环境中应始终验证SSL证书以确保通信安全[^4]。 - 如果需要更复杂的SSL配置(如自签名证书),可以加载特定的证书文件并将其添加到`SSLContext`中。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值