一、簡介
在上一篇文章中,我們詳細的介紹了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
@Configuration
public class HttpConfiguration {
/**
* 沒有實例化RestTemplate時,初始化RestTemplate
* @return
*/
@ConditionalOnMissingBean(RestTemplate.class)
@Bean
public 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;
@Component
public class HttpTemplate {
private static final Logger log = LoggerFactory.getLogger(HttpTemplate.class);
@Autowired
private 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();
}
}
- 最后,我們來做一下單元測試,使用案例如下,接口api還是基于上篇文章提供的服務
@RunWith(SpringRunner.class)
@SpringBootTest
public class HttpControllerJunit {
@Autowired
private HttpTemplate httpTemplate;
/**
* get請求測試
*/
@Test
public void testGet(){
//請求地址
String url = "http://localhost:8080/testGet";
//發起請求,直接返回對象
ResponseBean responseBean = httpTemplate.get(url, createHeader("get"), ResponseBean.class);
System.out.println(responseBean.toString());
}
/**
* get請求測試,restful風格
*/
@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());
}
/**
* 模擬表單提交,post請求
*/
@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());
}
/**
* 模擬JSON提交,post請求
*/
@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());
}
/**
* 重定向,post請求,json方式提交
*/
@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);
}
/**
* put請求,json方式提交
*/
@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());
}
/**
* delete請求,json方式提交
*/
@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());
}
/**
* 文件上傳,post請求
*/
@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());
}
/**
* 小文件下載
* @throws IOException
*/
@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, "未獲取到下載文件"));
}
/**
* 大文件下載
* @throws IOException
*/
@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);
}
/**
* 自定義請求頭部
* @param value
* @return
*/
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<xxx>這樣的,通過上面的方式來操作會直接報錯!
當遇到返回的對象是范型類型的時候,我們可以這樣操作!
以下面這個/testPostByJsonObj接口為例!
/**
* 模擬JSON請求,post方法測試
* @param request
* @return
*/
@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工具進行操作,也更簡單,代碼如下:
/**
* 模擬JSON提交,post請求,范型返回對象測試
*/
@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初始化之后,添加一個攔截器,然后在攔截器的請求頭部統一注入鑒權碼,就可以輕松實現全局加入某個參數,方式如下!
/**
* 初始化RestTemplate
* @return
*/
@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的功能其實非常強大,作者也僅僅學了點皮毛,在后續如果有新的功能,也會分享給大家,希望對網友們有所幫助!