RestTemplate 绕过ssl 验证

本文介绍如何配置RestTemplate,使其支持HTTP和HTTPS调用,并在必要时绕过SSL证书验证,确保能够进行不受限制的API通信。
摘要由CSDN通过智能技术生成

配置RestTemplate 支持http,https 调用,绕过ssl 验证。

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
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 java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 * Created By kl
 * Date: 2019/11/24
 * Description: TODO
 */
@Configuration
@Slf4j
public class RestTemplateConfig {

    @Bean
    public RestTemplate 
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 OkHttp3 中,可以通过配置 OkHttpClient 实例的 SSLSocketFactory 和 TrustManager 来实现绕过 SSL 验证,具体如下: ```java // 创建一个信任所有证书的 TrustManager TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }}; // 创建一个 SSLContext,并使用上面的 TrustManager 初始化 SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); // 创建一个 OkHttpClient 实例,并设置 SSLContext OkHttpClient client = new OkHttpClient.Builder() .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0]) .hostnameVerifier((hostname, session) -> true) .build(); // 发送请求 Request request = new Request.Builder() .url("https://example.com") .build(); Response response = client.newCall(request).execute(); ``` 在上面的代码中,我们创建了一个 TrustManager 实例,用于信任所有证书。然后使用这个 TrustManager 初始化一个 SSLContext,最后将这个 SSLContext 设置到 OkHttpClient 实例中。 需要注意的是,绕过 SSL 验证可能会带来安全风险,应该尽量避免在生产环境中使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值