一、简介在上一篇文章中,我们详细的介绍了RestTemplate工具类的用法,相比直接使用Apache的HttpClient进行网络传输,采用RestTemplate开发代码确实简化了很多,甚至可以做到傻瓜式操作,但是基于当前的团队人员开发习惯,我们可不可以继续基于RestTemplate再做一层封装呢?以便于操作Http网络请求,更加简单、便捷!
答案是肯定的!
本文要介绍的这个工具类,就是小编基于RestTemplate做了一层代码封装,里面涵盖了GET、POST、PUT、DELETE、文件上传与下载等等方法,同时支持自定义头部传参,通过灵活的传参,可以满足绝大部分业务场景下的网络请求场景!
同时,在上一篇介绍RestTemplate的《真不是我吹,Spring里这款牛逼的网络工具库我估计你都没用过!》文章里,我们还漏掉了一个最常用的场景,假如返回的对象,是一个范型类型,该怎么处理?
在本篇的文章里,我们也会详细的介绍这种问题的处理方法!
废话也不多说,直接上代码,希望对网友们能有所帮助!
二、代码实践下面以SpringBoot项目为例,如果是Spring项目,操作也类似,在配置类初始化的时候,实例化一个RestTemplate 。
- 首先添加httpclient依赖包,作为RestTemplate底层客户端
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.6</version></dependency>
- 接着创建一个配置,初始化RestTemplate
@Configurationpublic class HttpConfiguration {/*** 没有实例化RestTemplate时,初始化RestTemplate* @return*/@ConditionalOnMissingBean(RestTemplate.class)@Beanpublic RestTemplate restTemplate(){RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());return restTemplate;}/*** 使用HttpClient作为底层客户端* @return*/private ClientHttpRequestFactory getClientHttpRequestFactory() {int timeout = 5000;RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();return new HttpComponentsClientHttpRequestFactory(client);}}
- 然后,创建一个HttpTemplate工具类,将其生命周期交给Spring管理
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.ParameterizedTypeReference;import org.springframework.http.*;import org.springframework.stereotype.Component;import org.springframework.util.LinkedMultiValueMap;import org.springframework.util.MultiValueMap;import org.springframework.web.client.RequestCallback;import org.springframework.web.client.ResponseExtractor;import org.springframework.web.client.RestTemplate;import JAVA.net.URI;import java.util.Arrays;import java.util.Map;import java.util.Objects;@Componentpublic class HttpTemplate {private static final Logger log = LoggerFactory.getLogger(HttpTemplate.class);@Autowiredprivate RestTemplate restTemplate;/*** get请求,返回响应实体(响应业务对象不支持范型)* 支持restful风格* @param url* @param headers* @param responseType* @param uriVariables* @param <T>* @return*/public <T> T get(String url, Map<String, String> headers, Class<T> responseType, Object... uriVariables){ResponseEntity<T> rsp = commonExchange(url, HttpMethod.GET, new HttpEntity<>(createHeaders(headers)), responseType, uriVariables);return buildResponse(rsp);}/*** get请求,返回响应实体(响应业务对象支持范型)* 支持restful风格* @param url* @param headers* @param responseType* @param uriVariables* @param <T>* @return*/public <T> T get(String url, Map<String, String> headers, ParameterizedTypeReference<T> responseType, Object... uriVariables){ResponseEntity<T> rsp = commonExchange(url, HttpMethod.GET, new HttpEntity<>(createHeaders(headers)), responseType, uriVariables);return buildResponse(rsp);}/*** post请求,form表单提交(响应业务对象不支持范型)* 支持restful风格* @param url* @param headers* @param paramMap* @param responseType* @param uriVariables* @param <T>* @return*/public <T> T postByFrom(String url, Map<String, String> headers, Map<String, Object> paramMap, Class<T> responseType, Object... uriVariables){//指定请求头为表单类型HttpHeaders httpHeaders = createHeaders(headers);httpHeaders.setContentType(MediaType.AppLICATION_FORM_URLENCODED);ResponseEntity<T> rsp = commonExchange(url, HttpMethod.POST, new HttpEntity<>(createBody(paramMap), httpHeaders), responseType, uriVariables);return buildResponse(rsp);}/*** post请求,form表单提交(响应业务对象支持范型)* 支持restful风格* @param url* @param headers* @param paramMap* @param responseType* @param uriVariables* @param <T>* @return*/public <T> T postByFrom(String url, Map<String, String> headers, Map<String, Object> paramMap, ParameterizedTypeReference<T> responseType, Object... uriVariables){//指定请求头为表单类型HttpHeaders httpHeaders = createHeaders(headers);httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);ResponseEntity<T> rsp = commonExchange(url, HttpMethod.POST, new HttpEntity<>(createBody(paramMap), httpHeaders), responseType, uriVariables);return buildResponse(rsp);}/*** post请求,json提交(响应业务对象不支持范型)* 支持restful风格* @param url* @param headers* @param request* @param responseType* @param uriVariables* @param <T>* @return*/public <T> T postByJson(String url, Map<String, String> headers, Object request, Class<T> responseType, Object... uriVariables){//指定请求头为json类型HttpHeaders httpHeaders = createHeaders(headers);httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);ResponseEntity<T> rsp = commonExchange(url, HttpMethod.POST, new HttpEntity<>(request, httpHeaders), responseType, uriVariables);return buildResponse(rsp);}/*** post请求,json提交(响应业务对象支持范型)* 支持restful风格* @param url* @param headers* @param request* @param responseType* @param uriVariables* @param <T>* @return*/public <T> T postByJson(String url, Map<String, String> headers, Object request, ParameterizedTypeReference<T> responseType, Object... uriVariables){//指定请求头为json类型HttpHeaders httpHeaders = createHeaders(headers);httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);ResponseEntity<T> rsp = commonExchange(url, HttpMethod.POST, new HttpEntity<>(request, httpHeaders), responseType, uriVariables);return buildResponse(rsp);}/*** post请求,json提交,重定项* 支持restful风格* @param url* @param headers* @param request* @param uriVariables* @return*/public String postForLocation(String url, Map<String, String> headers, Object request, Object... uriVariables){//指定请求头为json类型HttpHeaders httpHeaders = createHeaders(headers);httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);URI uri = restTemplate.postForLocation(url, new HttpEntity<>(request, httpHeaders), uriVariables);if(Objects.nonNull(uri)){return uri.toString();}return null;}/*** put请求,json提交(响应业务对象不支持范型)* @param url* @param headers* @param request* @param uriVariables*/public <T> T put(String url, Map<String, String> headers, Object request, Class<T> responseType, Object... uriVariables){//指定请求头为json类型HttpHeaders httpHeaders = createHeaders(headers);httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);ResponseEntity<T> rsp = commonExchange(url, HttpMethod.PUT, new HttpEntity<>(request, httpHeaders), responseType, uriVariables);return buildResponse(rsp);}/*** put请求,json提交(响应业务对象支持范型)* @param url* @param headers* @param request* @param uriVariables*/public <T> T put(String url, Map<String, String> headers, Object request, ParameterizedTypeReference<T> responseType, Object... uriVariables){//指定请求头为json类型HttpHeaders httpHeaders = createHeaders(headers);httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);ResponseEntity<T> rsp = commonExchange(url, HttpMethod.PUT, new HttpEntity<>(request, httpHeaders), responseType, uriVariables);return buildResponse(rsp);}/*** delete请求(响应业务对象不支持范型)* @param url* @param headers* @param uriVariables* @return*/public <T> T delete(String url, Map<String, String> headers, Class<T> responseType, Object... uriVariables){ResponseEntity<T> rsp = commonExchange(url, HttpMethod.DELETE, new HttpEntity<>(createHeaders(headers)), responseType, uriVariables);return buildResponse(rsp);}/*** delete请求(响应业务对象支持范型)* @param url* @param headers* @param uriVariables* @return*/public <T> T delete(String url, Map<String, String> headers, ParameterizedTypeReference<T> responseType, Object... uriVariables){ResponseEntity<T> rsp = commonExchange(url, HttpMethod.DELETE, new HttpEntity<>(createHeaders(headers)), responseType, uriVariables);return buildResponse(rsp);}/*** post请求,文件表单上传提交(响应业务对象不支持范型)* 支持restful风格* @param url* @param headers* @param paramMap* @param responseType* @param uriVariables* @param <T>* @return*/public <T> T uploadFile(String url, Map<String, String> headers, MultiValueMap<String, Object> paramMap, Class<T> responseType, Object... uriVariables){//指定请求头为文件&表单类型HttpHeaders httpHeaders = createHeaders(headers);httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);ResponseEntity<T> rsp = commonExchange(url, HttpMethod.POST, new HttpEntity<>(paramMap, httpHeaders), responseType, uriVariables);return buildResponse(rsp);}/*** post请求,文件表单上传提交(响应业务对象支持范型)* 支持restful风格* @param url* @param headers* @param paramMap* @param responseType* @param uriVariables* @param <T>* @return*/public <T> T uploadFile(String url, Map<String, String> headers, MultiValueMap<String, Object> paramMap, ParameterizedTypeReference<T> responseType, Object... uriVariables){//指定请求头为文件&表单类型HttpHeaders httpHeaders = createHeaders(headers);httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);ResponseEntity<T> rsp = commonExchange(url, HttpMethod.POST, new HttpEntity<>(paramMap, httpHeaders), responseType, uriVariables);return buildResponse(rsp);}/*** 下载文件* @param url* @param headers* @param uriVariables* @return*/public byte[] downloadFile(String url, Map<String, String> headers, Object... uriVariables){ResponseEntity<byte[]> rsp = commonExchange(url, HttpMethod.GET, new HttpEntity<>(createHeaders(headers)), byte[].class, uriVariables);return buildResponse(rsp);}/*** 下载大文件* @param url* @param headers* @param responseExtractor* @param uriVariables*/public void downloadBigFile(String url, Map<String, String> headers, ResponseExtractor responseExtractor, Object... uriVariables){RequestCallback requestCallback = request -> {//指定请求头信息request.getHeaders().addAll(createHeaders(headers));//定义请求头的接收类型request.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));};restTemplate.execute(url, HttpMethod.GET, requestCallback,responseExtractor, uriVariables);}/*** 公共http请求方法(响应业务对象不支持范型)* @param url* @param method* @param requestEntity* @param responseType* @param uriVariables* @param <T>* @return*/public <T> ResponseEntity<T> commonExchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables){return restTemplate.exchange(url, method, requestEntity, responseType, uriVariables);}/*** 公共http请求方法(响应业务对象支持范型)* @param url* @param method* @param requestEntity* @param responseType* @param uriVariables* @param <T>* @return*/public <T> ResponseEntity<T> commonExchange(String url, HttpMethod method, HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Object... uriVariables){return restTemplate.exchange(url, method, requestEntity, responseType, uriVariables);}/*** 封装头部参数* @param headers* @return*/private HttpHeaders createHeaders(Map<String, String> headers){return new HttpHeaders(){{if(headers != null && !headers.isEmpty()){headers.entrySet().forEach(item -> {set(item.getKey(), item.getValue());});}}};}/*** 封装请求体* @param paramMap* @return*/private MultiValueMap<String, Object> createBody(Map<String, Object> paramMap){MultiValueMap<String, Object> valueMap = new LinkedMultiValueMap<>();if(paramMap != null && !paramMap.isEmpty()){paramMap.entrySet().forEach(item -> {valueMap.add(item.getKey(), item.getValue());});}return valueMap;}/*** 返回响应对象* @param rsp* @param <T>* @return*/private <T> T buildResponse(ResponseEntity<T> rsp){if(!rsp.getStatusCode().is2xxSuccessful()){throw new RuntimeException(rsp.getStatusCode().getReasonPhrase());}return rsp.getBody();}}
推荐阅读
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 别再自己瞎写工具类了,SpringBoot 内置工具类应有尽有,建议收藏
- 黑客大神用什么杀毒?Windows自带的就够,只是加了亿点微小强化
- 年底十三薪是不是就没有年终奖了?速看!不止年终奖、十三薪,年底还有这几笔钱能领
- 开空调制热一个月电费多少-空调制冷一个月多少电费-_3
- 小学成绩不好为什么到初中就变好了?小学成绩很好,到了初中为什么就不好了呢-
- 太史慈什么时候投靠了孙策-?东吴名将太史慈在投靠孙策前,是何人的部下-
- 古代太监太可怜了?古代宫女嫁给太监是怎么过日子的
- 咸丰完了是谁继位的?咸丰在位几年
- 红茶放久了好苦,红茶可以四季喝吗
- 罐装密封红茶保质期,红茶茶袋保质期多久