Disabling SSL Certificate Validation in Spring RestTemplate

后端 未结 12 1467
花落未央
花落未央 2020-11-28 20:05

I am having two Spring based web apps A and B, on two different machines.

I want to make a https call from web app A to web app B, however I am using a self-signed c

12条回答
  •  暖寄归人
    2020-11-28 20:46

    Java code example for HttpClient > 4.3

    package com.example.teocodownloader;
    
    import org.apache.http.conn.ssl.NoopHostnameVerifier;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
    import org.springframework.web.client.RestTemplate;
    
    public class Example {
        public static void main(String[] args) {
            CloseableHttpClient httpClient
                    = HttpClients.custom()
                    .setSSLHostnameVerifier(new NoopHostnameVerifier())
                    .build();
            HttpComponentsClientHttpRequestFactory requestFactory
                    = new HttpComponentsClientHttpRequestFactory();
            requestFactory.setHttpClient(httpClient);
            RestTemplate restTemplate = new RestTemplate(requestFactory);
        }
    }
    

    By the way, don't forget to add the following dependencies to the pom file:

    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.springframework.boot
        spring-boot-starter-security
    
    
        org.apache.httpcomponents
        httpclient
    
    

    You could find Java code example for HttpClient < 4.3 as well.

提交回复
热议问题