如何让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<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; } }
封装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> 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; } } }
测试样例
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; } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。