RestTemplate忽略Https证书

  1. 实现自定义的SimpleClientHttpRequestFactory

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    private static SimpleClientHttpRequestFactory getUnsafeClientHttpRequestFactory() {
    TrustManager[] byPassTrustManagers = new TrustManager[]{new X509TrustManager() {

    @Override
    public X509Certificate[] getAcceptedIssuers() {
    return new X509Certificate[0];
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) {
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) {
    }
    }};
    final SSLContext sslContext;
    try {
    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, byPassTrustManagers, new SecureRandom());
    sslContext.getSocketFactory();
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
    throw new RuntimeException(e);
    }

    return new SimpleClientHttpRequestFactory() {
    @Override
    protected void prepareConnection(HttpURLConnection connection,
    String httpMethod) throws IOException {
    super.prepareConnection(connection, httpMethod);
    if (connection instanceof HttpsURLConnection) {
    ((HttpsURLConnection) connection).setSSLSocketFactory(
    sslContext.getSocketFactory());
    }
    }
    };
    }
  2. 在RestTemplate中设置requestFactory

    1
    2
    3
    RestTemplate restTemplate = new RestTemplate();
    SimpleClientHttpRequestFactory requestFactory = getUnsafeClientHttpRequestFactory();
    restTemplate.setRequestFactory(requestFactory);
作者

qrua7

发布于

2022-02-18

更新于

2025-10-28

许可协议

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×