Java uses Https request to ignore SSL certification

  •   foreword

         Recently, I was in charge of a connection with a third-party service. During the connection period, because the third-party service is an HTTPS request, as we all know, the HTTPS request will use the local certificate public key to access the service SSL certificate. I do not have a corresponding SSL locally. Certificate, so the service cannot be requested, and the following error is reported when requesting the interface. Looking through the resources, it is found that SSL certification can be ignored.

 unable to find valid certification path to requested target

​​​​​​​

   1. Write the RestTemplate configuration class

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(generateHttpRequestFactory());
    }

    /**
     * 忽略SSL证书
     * @return
     */
    private HttpComponentsClientHttpRequestFactory generateHttpRequestFactory() {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());

        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
        CloseableHttpClient httpClient = httpClientBuilder.build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(httpClient);
        return factory;
    }

}

2. Write test classes

@SpringBootTest
public class IgnoreSSLTest {

    @Autowired
    private RestTemplate restTemplate;

    private String url = "https://xxx.xxxx";
    @Test
    public void test() {
        //使用restTemplate实现服务调用
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, null, String.class);
        System.out.println("返回值为:" + responseEntity);
    }
}

The test result checks whether the interface is successfully requested, and ignores the SSL certificate.

Of course, there are many ways to install certificates.

Guess you like

Origin blog.csdn.net/xiaozhang_man/article/details/121881253