• 如何让Springboot RestTemplate同时支持发送HTTP及HTTPS请求呢?


    转自:

    如何让Springboot RestTemplate同时支持发送HTTP及HTTPS请求呢?

    下文笔者讲述RestTemplate同时支持发送HTTP及HTTPS请求的方法分享,如下所示

    RestTemplate简介

     
    RestTemplate简介:
       从Spring3.0开始支持的一个远程HTTP请求工具
    RestTemplate用途:
        可对外提供常见的Rest服务请求调用方式,使用RestTemplate请求可使客户端开发的效率提高
        RestTemplate支持GET请求、POST 请求、PUT 请求、DELETE请求及一些通用的请求执行方法 exchange及execute
    
    RestTemplate:
       是spring-web-xxx.jar包中提供的Http协议实现类
       当导入spring-boot-starter-web的项目可以接使用RestTemplate类
    

    RestTemplate示例

    1.新建HttpsClientRequestFactory.java类实现SimpleClientHttpRequestFactory

    package com.java265.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;
    /** 
     * @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();
            }
        }
     
    }
    

    创建RestTemplate配置类注册Bean

    package com.java265.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;
     
    /** 
     * *RestTemplateConfig配置文件
     */
    @Configuration
    public class RestTemplateConfig {
        @Bean
        public RestTemplate restTemplate(){
            //同时支持http和https请求方式
            RestTemplate restTemplate = new RestTemplate (new HttpsClientRequestFactory());
            List> 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;
        }
    }
    

    封装RestTemplate

    package com.java265.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;
     
    @Component
    @Slf4j
    public class httpRequestUtil {
        @Autowired
        private RestTemplate restTemplate;
        @Autowired
        //get,delete,put请求
        private ObjectMapper objectMapper;
        public  T getRequest(String url, HttpMethod httpMethod, HttpEntity httpEntity,Class 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 postRequest(String url, HttpEntity httpEntity,Class 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;
            }
        }
    }
    

    测试样例

    package com.java265.controller;
     
    import com.java265.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;
     
    @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://java265.com/getApiInfo")
                    .append("?key=").append("88888")
                    .append("&name=").append("java");
            ObjectNode rootNode = objectMapper.createObjectNode();
            rootNode.put( "v","8888");
            rootNode.put( "t", "男");
            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;
            }
        }
    }
  • 相关阅读:
    软件测试人员的职业发展之路,写给那些还在迷茫的测试人
    Doodles版洞洞鞋3天售罄 蓝筹NFT卖货自救
    JavaScript 字符串连接的工作原理——“+”运算符与“+=”运算符
    这才是数字孪生污水处理厂该有的样子 | 智慧水务
    【算法三】冒泡排序
    视频批量剪辑与分割:这些技巧帮你提高生成m3u8文件的效率
    Flink1.15源码解析--启动JobManager----WebMonitorEndpoint启动
    计算机复习
    02Halcon标定实验
    Nginx Note02——事件驱动模型
  • 原文地址:https://blog.csdn.net/qq_25073223/article/details/127976039