Springboot RestTemplate同时支持发送HTTP及HTTPS请求

RestTemplate简述:
RestTemplate 是从Spring3.0开始支持的一个远程HTTP请求工具,RestTemplate提供了常见的Rest服务(Rest风格、Rest架构)的客户端请求的模版,能够大大提高客户端的编写效率。
例如支持GET 请求、POST 请求、PUT 请求、DELETE 请求以及一些通用的请求执行方法 exchange 以及 execute。这些操作在 RestTemplate 中都得到了实现。调用RestTemplate的默认构造函数,可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式。ClientHttpRequestFactory接口主要提供了两种实现方式,一种是SimpleClientHttpRequestFactory,使用J2SE提供的方式(既java.net包提供的方式)创建底层的Http请求连接,还有一种方式是使用HttpComponentsClientHttpRequestFactory方式,底层使用HttpClient访问远程的Http服务,使用HttpClient可以配置连接池和证书等信息。接下来我们统一使用Resttemplate的exchange方法调用get、put、delete、post请求。
RestTemplate
HttpClient 是 apache 的开源,需要引入两个包:httpclient-4.2.4.jar 和 httpcore-4.2.2.jar。
RestTemplate与HttpClien
RestTemplate
RestTemplate是spring-web-xxx.jar包中提供的Http协议实现类。也就是说导入spring-boot-starter-web的项目可以直接使用RestTemplate类,就是基于模板方法设计模式的,封装了所有需要使用的API。
HttpClien
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,需要引入两个包:httpclient-x.x.x.jar 和 httpcore-x.x.x.jar。

RestTemplate具体操作如下:

1、新建HttpsClientRequestFactory.java类实现SimpleClientHttpRequestFactory

代码如下:

package com.example.oauth_test.config;

import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.net.HttpURLConnection;
import java. security.KeyStore;
import java. security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
 * @author wly
 * @date 2022-05-17 11:59:40
 * @describe同时支持http及https请求★/
 */
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod){
        try{
            if(!(connection instanceof HttpsURLConnection)){
                //http协议
                super.prepareConnection (connection, httpMethod) ;
            }
            if ((connection instanceof HttpsURLConnection)) {
                //https协议
                KeyStore trustStore = KeyStore.getInstance (KeyStore.getDefaultType());
                //信任任何链接
                TrustStrategy anyTrustStrategy = new TrustStrategy(){
                    @Override
                    public boolean isTrusted (X509Certificate[] chain,String authType) throws CertificateException{
                        return true;
                    }
                };
                SSLContext ctx = SSLContexts.custom().useSSL().loadTrustMaterial(trustStore , anyTrustStrategy).build();
                ((HttpsURLConnection) connection).setSSLSocketFactory(ctx.getSocketFactory());
                HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
                super.prepareConnection(httpsConnection,httpMethod) ;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

2、创建RestTemplate配置类注册Bean

代码:

package com.example.oauth_test.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author wly
 * @date 2022-05-17 14:59:30
 * *RestTemplateConfig配置文件
 */
@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(){
        //同时支持http和https请求方式
        RestTemplate restTemplate = new RestTemplate (new HttpsClientRequestFactory());
        List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
        //重新设置StringHttpMessageConverter字符集为UTF-8,解决中文乱码问题
        HttpMessageConverter<?> converterTarget = null;
        for (HttpMessageConverter<?> item : converterList){
            if (StringHttpMessageConverter.class == item.getClass()){
                converterTarget = item;
                break;
            }
        }
        if (null != converterTarget){
            converterList.remove(converterTarget);
        }

        converterList.add(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }
}

3、封装RestTemplate

代码:

package com.example.oauth_test.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

/**
 * @author wly
 * @date 2022-05-17 15:28:24
 */
@Component
@Slf4j
public class httpRequestUtil {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    //get,delete,put请求
    private ObjectMapper objectMapper;
    public <T> T getRequest(String url, HttpMethod httpMethod, HttpEntity httpEntity,Class<T> clazz){
        try{
            ResponseEntity exchange = restTemplate.exchange(url,httpMethod,httpEntity,clazz);
            return (T) exchange.getBody();

        }catch (RestClientException e){
            log.error(e.getMessage(), e);
            return null;
        }
    }
    //post请求
    public <T> T postRequest(String url, HttpEntity httpEntity,Class<T> clazz){
        try{
            String exchange = restTemplate.postForObject(url,httpEntity,String.class);
            return(T) objectMapper.readValue(exchange,clazz);

        }catch (JsonMappingException e){
            log.error(e.getMessage(), e);
            return null;
        }catch (JsonProcessingException e){
            log.error(e.getMessage(), e);
            return null;
        }
    }
}

4、调用样例

代码:

package com.example.oauth_test.controller;

import com.example.oauth_test.util.httpRequestUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wly
 * @date 2022-05-17 15:45:12
 */
@RestController
@Slf4j
public class test {
    @Autowired
    public httpRequestUtil httpRequestUtil;
    @Autowired
    private ObjectMapper objectMapper;
    private String applicationJson = "application/json";
    private String applicationStr = "application/X-WWW-form-urlencoded";
    @GetMapping("/test")
    public String test() {
        StringBuilder userUrl = new StringBuilder("http://10.10.10.10:8010/assist/userinfo")
                .append("?usrtId=").append("111111")
                .append("&name=").append("zhangsan");
        ObjectNode rootNode = objectMapper.createObjectNode();
        rootNode.put( "notesId","1001");
        rootNode.put( "fex", "女");
        try{
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.add("Content-Type", applicationJson);
            HttpEntity httpEntity = new HttpEntity(rootNode.toString(),headers);
            String result = httpRequestUtil.postRequest(userUrl.toString() , httpEntity, String.class);
            return result;
        }catch (Exception e){
            log.error("调用接口失败:"+e.getMessage());
            return null;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/huanglm_OneWholeLife/article/details/124818611