springboot uses restTemplate to send https request to ignore ssl certificate

In the project, when we need to call an HTTP interface remotely, we often use the RestTemplate class. This class is a tool class provided by the Spring framework. Spring's official website introduces it as follows:

RestTemplate: The original Spring REST client with a synchronous, template method API.

From the above introduction, we can know that RestTemplate is a synchronous Rest API client. Let's introduce the common functions of RestTemplate.

getForObject — optionsForAllow is divided into one group, such methods are regular Rest API (GET, POST, DELETE, etc.) method calls; exchange:
receive a RequestEntity parameter, you can set HTTP method, URL, headers and body yourself, and return ResponseEntity;
execute : Through the callback interface, more comprehensive custom control can be done on the request and return.

A ClientHttpRequestFactory is required when creating a RestTemplate. Through this request factory, we can uniformly set the timeout period of the request, set the proxy and some other details. After configuring the above code, we can directly inject the RestTemplate into the code and use it.

Sometimes we also need to configure the maximum number of connections through ClientHttpRequestFactory, ignoring SSL certificates , etc. You can check the code settings yourself when you need them
Explanation: Two ways of writing

//使用 RestTemplateBuilder.build() 代替 new RestTemplate()

    //使用 RestTemplateBuilder.build()
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
    
    
       return builder.build();
    }
 
    //代替 new RestTemplate()
    @Bean
    public RestTemplate restTemplate() {
    
    
        return new RestTemplate();
    }

Let's start the formal code
Step 1:
First add a RestTemplateConfig configuration file

package com.school.init.config;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
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;

/**
 *  restTemplate配置类
 *
 * @author Json
 */

@Configuration
public class RestTemplateConfig {
    
    

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

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
    
    
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }

    public static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory()
            throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException
    {
    
    
        TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        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;
    }
}

Step 2:
Modify and initialize the RestTemplate class:

  @Bean
    public RestTemplate getRestTemplate() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    
    
       return new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
    }

Step 3: Encapsulate the calling method

   /**
     * 调用第三方服务器接口
     * 传入JSONObject表示post请求
     * 不传表示get请求
     * @param url 路由
     * @param jsonObject 参数
     * @param method 方法
     * @return
     */
    public  JSONObject getApi(String url, JSONObject jsonObject, HttpMethod method, List<String> stringList) throws Exception{
    
    
        RestTemplate restTemplate = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
        //此处加编码格式转换
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(org.springframework.http.MediaType.APPLICATION_JSON_UTF8);
        httpHeaders.put("Authorization",stringList);
        HttpEntity httpEntity = new HttpEntity(jsonObject, httpHeaders);
        //访问第三方服务器
        ResponseEntity<String> exchange = restTemplate.exchange(url, method, httpEntity, String.class);
        return JSONObject.parseObject(exchange.getBody(),JSONObject.class);
    }

Call method:

        AiRobotRequest data = aiRobotRequest.getData();
        String accessToken = "";
        JSONObject jsonData = (JSONObject) JSON.toJSON(data);
        String url="";

        List<String> stringList=new ArrayList<>();
        stringList.add("Bearer "+accessToken);
        JSONObject s =getApi(url, jsonData,HttpMethod.POST,stringList);
        log.info("微信消息返回值" + s);

Guess you like

Origin blog.csdn.net/Drug_/article/details/129191580