答案是肯定的!
本文要介绍的这个工具类,就是小编基于RestTemplate做了一层代码封装,里面涵盖了GET、POST、PUT、DELETE、文件上传与下载等等方法,同时支持自定义头部传参,通过灵活的传参,可以满足绝大部分业务场景下的网络请求场景!
同时,在上一篇介绍RestTemplate的《真不是我吹,Spring里这款牛逼的网络工具库我估计你都没用过!》文章里,我们还漏掉了一个最常用的场景,假如返回的对象,是一个范型类型,该怎么处理?
在本篇的文章里,我们也会详细的介绍这种问题的处理方法!
废话也不多说,直接上代码,希望对网友们能有所帮助!
二、代码实践
下面以SpringBoot项目为例,如果是Spring项目,操作也类似,在配置类初始化的时候,实例化一个RestTemplate。
- 添加httpclient依赖包,作为RestTemplate底层客户端
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
<version>4.5.6version>
dependency>
- 创建一个配置,初始化RestTemplate
@Configuration
public class HttpConfiguration {
@ConditionalOnMissingBean(RestTemplate.class)
@Bean
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
return restTemplate;
}
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;
@Component
public class HttpTemplate {
private static final Logger log = LoggerFactory.getLogger(HttpTemplate.class);
@Autowired
private RestTemplate restTemplate;
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
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;
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
public <T> ResponseEntity<T> commonExchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables){
return restTemplate.exchange(url, method, requestEntity, responseType, uriVariables);
}
public <T> ResponseEntity<T> commonExchange(String url, HttpMethod method, HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Object... uriVariables){
return restTemplate.exchange(url, method, requestEntity, responseType, uriVariables);
}
private HttpHeaders createHeaders(Map<String, String> headers){
return new HttpHeaders(){{
if(headers != null && !headers.isEmpty()){
headers.entrySet().forEach(item -> {
set(item.getKey(), item.getValue());
});
}
}};
}
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;
}
private <T> T buildResponse(ResponseEntity<T> rsp){
if(!rsp.getStatusCode().is2xxSuccessful()){
throw new RuntimeException(rsp.getStatusCode().getReasonPhrase());
}
return rsp.getBody();
}
}
- 我们来做一下单元测试,使用案例如下,接口api还是基于上篇文章提供的服务
@RunWith(SpringRunner.class)
@SpringBootTest
public class HttpControllerJunit {
@Autowired
private HttpTemplate httpTemplate;
@Test
public void testGet(){
//请求地址
String url = "http://localhost:8080/testGet";
//发起请求,直接返回对象
ResponseBean responseBean = httpTemplate.get(url, createHeader("get"), ResponseBean.class);
System.out.println(responseBean.toString());
}
@Test
public void testGetByRestFul(){
//请求地址
String url = "http://localhost:8080/testGetByRestFul/{1}";
//发起请求,直接返回对象(restful风格)
ResponseBean responseBean = httpTemplate.get(url, createHeader("testGetByRestFul"), ResponseBean.class, "张三");
System.out.println(responseBean.toString());
}
@Test
public void testPostByForm(){
//请求地址
String url = "http://localhost:8080/testPostByFormAndObj";
//表单参数
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("userName", "唐三藏");
paramMap.put("userPwd", "123456");
//发起请求
ResponseBean responseBean = httpTemplate.postByFrom(url, createHeader("testPostByFormAndObj"), paramMap, ResponseBean.class);
System.out.println(responseBean.toString());
}
@Test
public void testPostByJson(){
//请求地址
String url = "http://localhost:8080/testPostByJson";
//入参
RequestBean request = new RequestBean();
request.setUserName("唐三藏");
request.setUserPwd("123456789");
//发送post请求,并打印结果,以String类型接收响应结果JSON字符串
ResponseBean responseBean = httpTemplate.postByJson(url, createHeader("testPostByJson"), request, ResponseBean.class);
System.out.println(responseBean.toString());
}
@Test
public void testPostByLocation(){
//请求地址
String url = "http://localhost:8080/testPostByLocation";
//入参
RequestBean request = new RequestBean();
request.setUserName("唐三藏");
request.setUserPwd("123456789");
//用于提交完成数据之后的页面跳转
String uri = httpTemplate.postForLocation(url, createHeader("testPostByLocation"), request);
System.out.println(uri);
}
@Test
public void testPutByJson(){
//请求地址
String url = "http://localhost:8080/testPutByJson";
//入参
RequestBean request = new RequestBean();
request.setUserName("唐三藏");
request.setUserPwd("123456789000");
//模拟JSON提交,put请求
ResponseBean responseBean = httpTemplate.put(url, createHeader("testPutByJson"), request, ResponseBean.class);
System.out.println(responseBean.toString());
}
@Test
public void testDeleteByJson(){
//请求地址
String url = "http://localhost:8080/testDeleteByJson";
//模拟JSON提交,delete请求
ResponseBean responseBean = httpTemplate.delete(url, createHeader("testDeleteByJson"), ResponseBean.class);
System.out.println(responseBean.toString());
}
@Test
public void uploadFile(){
//需要上传的文件
String filePath = "/Users/panzhi/Desktop/Jietu20220205-194655.jpg";
//请求地址
String url = "http://localhost:8080/upload";
//提交参数设置
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("uploadFile", new FileSystemResource(new File(filePath)));
//服务端如果接受额外参数,可以传递
param.add("userName", "张三");
ResponseBean responseBean = httpTemplate.uploadFile(url, createHeader("uploadFile"), param, ResponseBean.class);
System.out.println(responseBean.toString());
}
@Test
public void downloadFile() throws IOException {
String userName = "张三";
String fileName = "f9057640-90b2-4f86-9a4b-72ad0e253d0d.jpg";
//请求地址
String url = "http://localhost:8080/downloadFile/{1}/{2}";
//发起请求,直接返回对象(restful风格)
byte[] stream = httpTemplate.downloadFile(url, createHeader("downloadFile"), userName,fileName);
// 将下载下来的文件内容保存到本地
String targetPath = "/Users/panzhi/Desktop/" + fileName;
Files.write(Paths.get(targetPath), Objects.requireNonNull(stream, "未获取到下载文件"));
}
@Test
public void downloadBigFile() {
String userName = "张三";
String fileName = "f9057640-90b2-4f86-9a4b-72ad0e253d0d.jpg";
String targetPath = "/Users/panzhi/Desktop/" + fileName;
//请求地址
String url = "http://localhost:8080/downloadFile/{1}/{2}";
//对响应进行流式处理而不是将其全部加载到内存中
httpTemplate.downloadBigFile(url, createHeader("downloadBigFile"), clientHttpResponse -> {
Files.copy(clientHttpResponse.getBody(), Paths.get(targetPath));
return null;
}, userName, fileName);
}
private Map<String, String> createHeader(String value){
Map<String, String> headers = new HashMap<>();
headers.put("token", value);
return headers;
}
}
- 假如返回的对象是一个范型,应该怎么处理呢?
在上篇文章中,我们介绍的返回对象都是非范型,例如返回的都是ResponseBean这个业务对象,用法也很简单,以POST请求+JSON提交方式为例,通过如下方式即可实现返回对象的序列化!
ResponseBean responseBean = httpTemplate.postByJson(url, createHeader("testPostByJson"), request, ResponseBean.class);
但是,假如返回的对象是ResponseBean这样的,通过上面的方式来操作会直接报错!
当遇到返回的对象是范型类型的时候,我们可以这样操作!
以下面这个/testPostByJsonObj接口为例!
@RequestMapping(value = "testPostByJsonObj", method = RequestMethod.POST)
public ResponseBeanObj<ResponseBean> testPostByJsonObj(@RequestBody RequestBean requestBean, HttpServletRequest request){
HttpServletRequestLog.systemLog(request);
//范型测试
ResponseBean responseBean = new ResponseBean();
responseBean.setCode("200000");
responseBean.setMsg("responseBean");
//范型测试
ResponseBeanObj<ResponseBean> result = new ResponseBeanObj<>();
result.setCode("200");
result.setMsg("请求成功,方法:testPostByJsonObj,请求参数:" + JSON.toJSONString(requestBean));
result.setObj(responseBean);
System.out.println(JSON.toJSONString(result));
return result;
}
使用RestTemplate工具发起网络请求,代码如下!
//将返回的范型对象包装到ParameterizedTypeReference对象里面
ParameterizedTypeReference<ResponseBeanObj<ResponseBean>> typeRef = new ParameterizedTypeReference<ResponseBeanObj<ResponseBean>>() {};
//使用restTemplate发起网络请求
ResponseBeanObj<ResponseBean> responseBean = restTemplate.exchange(url, HttpMethod.POST, request, typeRef);
采用restTemplate.exchange()方法,即可实现返回对象范型类型的反序列化!
如果使用上面封装的HttpTemplate工具进行操作,也更简单,代码如下:
@Test
public void testPostByJsonObj(){
//请求地址
String url = "http://localhost:8080/testPostByJsonObj";
//入参
RequestBean request = new RequestBean();
request.setUserName("唐三藏");
request.setUserPwd("123456789");
//发送post请求
ParameterizedTypeReference<ResponseBeanObj<ResponseBean>> typeRef = new ParameterizedTypeReference<ResponseBeanObj<ResponseBean>>() {};
//范型测试
ResponseBeanObj<ResponseBean> responseBean = httpTemplate.postByJson(url, createHeader("testPostByJsonObj"), request, typeRef);
System.out.println(JSON.toJSONString(responseBean));
}
三、自定义拦截器
在某些场景下,当你使用restTemplate发起网络请求时,所有的请求头部需要带上统一的参数,例如Authorization鉴权码,这个时候改怎么办呢?
可能有的同学,想到的就是在传参数的时候,带上请求头部参数!这种方法也可以解决问题!
有没有好的办法统一入口加入呢?
答案肯定是有的,我们可以利用RestTemplate提供的拦截器链来解决这个问题。
例如在RestTemplate初始化之后,添加一个拦截器,然后在拦截器的请求头部统一注入鉴权码,就可以轻松实现全局加入某个参数,方式如下!
@Bean
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
// 添加一个拦截器,在请求头部添加 Authorization 鉴权码
restTemplate.getInterceptors().add((request, body, execution) -> {
request.getHeaders().add("Authorization", "xxxxxXXXXX");
return execution.execute(request, body);
});
return restTemplate;
}
四、小结
通过本章的讲解,想必读者初步的了解了如何基于RestTemplate做第二次封装,以便于更佳适配当前团队开发人员的习惯。
RestTemplate的功能其实非常强大,作者也仅仅学了点皮毛,在后续如果有新的功能,也会分享给大家,希望对网友们有所帮助!