如何让Springboot RestTemplate同时支持发送HTTP及HTTPS请求呢?
admin
2024-02-06 19:20:24

转自:

如何让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 {@Overrideprotected 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(){@Overridepublic 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 {@Beanpublic 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 {@Autowiredprivate 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 {@Autowiredpublic httpRequestUtil httpRequestUtil;@Autowiredprivate 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;}}
}

相关内容

热门资讯

人力资源专业就业前景 人力资源... 一份对本年度人力资源管理专业就业状况的调查表明,人力资源管理职业的前景持续看好,人力资源管理专业就业...
最新或2023(历届)北京市大...  谁是北京市第一高校?谁是北京市最佳大学?为了满足我国两岸四地高考考生及家长了解北京市高校的办学水平...
河北最新或2023(历届)普通... 最新或2023(历届)我省普通高校招生体育类专业(体育教育、社会体育指导与管理等专业,下同)考试定于...
河北最新或2023(历届)高职... 最新或2023(历届)我省有66所院校参加普通院校高职单独考试招生(以下简称“高职单招”),并试行不...
广西高考最新或2023(历届)... 各市、县招生考试委员会、教育局,各有关高等职业院校:  为贯彻落实《国务院关于深化考试招生制度改革的...