当前位置:网站首页>Resttemplate realizes the unified encapsulation (printable log) of post, put, delete, get, set request and file upload (batch files and parameters) through generics
Resttemplate realizes the unified encapsulation (printable log) of post, put, delete, get, set request and file upload (batch files and parameters) through generics
2022-07-25 17:42:00 【Suddenly】
Catalog
1、RestTemplate To configure
introduce POM:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
RestTemplateLog( Request log printing ) :
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
@Slf4j
@Component
public class RestTemplateLog implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
traceRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
traceResponse(response);
return response;
}
private void traceRequest(HttpRequest request, byte[] body) {
String path = request.getURI().getPath();
String header = String.valueOf(request.getHeaders());
String param = new String(body, StandardCharsets.UTF_8);
log.info("RestTemplate Request information :【 request URL:{}, Request header :{}, Request parameters :{}】", path, header, param);
}
private void traceResponse(ClientHttpResponse response) throws IOException {
StringBuilder inputStringBuilder = new StringBuilder();
try (BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(response.getBody(), StandardCharsets.UTF_8))) {
String line = bufferedReader.readLine();
while (line != null) {
inputStringBuilder.append(line);
inputStringBuilder.append('\n');
line = bufferedReader.readLine();
}
}
int status = response.getStatusCode().value();
String body = String.valueOf(inputStringBuilder).trim();
log.info("RestTemplate Response information :【 Status code :{}, Response parameter :{}】", status, body);
}
}
RestTemplateConfig( Request configuration ):
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
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.Iterator;
import java.util.List;
@Configuration
public class RestTemplateConfig {
@Resource
private RestTemplateLog restTemplateLog;
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
RestTemplate restTemplate = builder.build();
// Add interceptor
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(restTemplateLog);
restTemplate.setInterceptors(interceptors);
restTemplate.setRequestFactory(clientHttpRequestFactory());
// Use utf-8 Code set conver Replace the default conver( default string conver The coding set of is "ISO-8859-1")
List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
while (iterator.hasNext()) {
HttpMessageConverter<?> converter = iterator.next();
if (converter instanceof StringHttpMessageConverter) {
iterator.remove();
}
}
messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
@Bean
public HttpClientConnectionManager poolingConnectionManager() {
PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager();
// Maximum number of connections in connection pool
poolingConnectionManager.setMaxTotal(10000);
// Concurrency per host
poolingConnectionManager.setDefaultMaxPerRoute(10000);
return poolingConnectionManager;
}
@Bean
public HttpClientBuilder httpClientBuilder() {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// Set up HTTP Connection manager
httpClientBuilder.setConnectionManager(poolingConnectionManager());
return httpClientBuilder;
}
@Bean
public ClientHttpRequestFactory clientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
clientHttpRequestFactory.setHttpClient(httpClientBuilder().build());
// Connection timeout , millisecond
clientHttpRequestFactory.setConnectTimeout(6000);
// Read write timeout , millisecond
clientHttpRequestFactory.setReadTimeout(6000);
return clientHttpRequestFactory;
}
}
2、 Request body encapsulation
adopt RestTemplate Package unified POST、PUT、DELETE、GET, Suitable for returning any type of object , Respectively doHttp And doHttpList Two methods , A method receives a single object type , A method receives a collection object ;
FileRequestServer:
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class FileRequestServer {
@Resource
private RestTemplate restTemplate;
/** * The default is not to take the lead , And the request type is json * * @param url * @param method * @param obj * @param tClass For the entity type to be returned * @return */
public <T> T doHttp(String url, HttpMethod method, Object obj, Class<T> tClass) {
return doHttp(url, MediaType.APPLICATION_JSON, null, method, obj, tClass);
}
/** * The default is not to take the lead * * @param url * @param contentType * @param method * @param obj * @param tClass For the entity type to be returned * @return */
public <T> T doHttp(String url, MediaType contentType, HttpMethod method, Object obj, Class<T> tClass) {
return doHttp(url, contentType, null, method, obj, tClass);
}
/** * Default lead , And the request type is json * * @param url * @param headerMap * @param method * @param obj * @param tClass For the entity type to be returned * @return */
public <T> T doHttp(String url, Map<String, String> headerMap, HttpMethod method, Object obj, Class<T> tClass) {
return doHttp(url, null, headerMap, method, obj, tClass);
}
/** * @param url * @param contentType * @param headerMap * @param method * @param obj * @param tClass For the entity type to be returned * @return */
public <T> T doHttp(String url, MediaType contentType, Map<String, String> headerMap, HttpMethod method, Object obj, Class<T> tClass) {
HttpHeaders headers = new HttpHeaders();
contentType = contentType == null ? MediaType.APPLICATION_JSON : contentType;
headers.setContentType(contentType);
if (headerMap != null && headerMap.size() > 0) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
}
HttpEntity entity = new HttpEntity(obj, headers);
ResponseEntity<T> exchange = restTemplate.exchange(url, method, entity, tClass);
return exchange.getBody();
}
/** * The default is not to take the lead , And the request type is json, return List A collection of objects * * @param url * @param method * @param obj * @param tClass * @return */
public <T> List<T> doHttpList(String url, HttpMethod method, Object obj, Class<T> tClass) {
return doHttpList(url, MediaType.APPLICATION_JSON, null, method, obj, tClass);
}
/** * The default is not to take the lead , return List A collection of objects * * @param url * @param contentType * @param method * @param obj * @param tClass For the entity type to be returned * @return */
public < T> List<T> doHttpList(String url, MediaType contentType, HttpMethod method, Object obj, Class<T> tClass) {
return doHttpList(url, contentType, null, method, obj, tClass);
}
/** * Default lead , And the request type is json, return List A collection of objects * * @param url * @param headerMap * @param method * @param obj * @param tClass * @return */
public < T> List<T> doHttpList(String url, Map<String, String> headerMap, HttpMethod method, Object obj, Class<T> tClass) {
return doHttpList(url, null, headerMap, method, obj, tClass);
}
/** * return List A collection of objects * * @param url * @param contentType * @param headerMap * @param method * @param obj * @param tClass For the entity type to be returned * @param <T> * @return */
public < T> List<T> doHttpList(String url, MediaType contentType, Map<String, String> headerMap, HttpMethod method, Object obj, Class<T> tClass) {
HttpHeaders headers = new HttpHeaders();
contentType = contentType == null ? MediaType.APPLICATION_JSON : contentType;
headers.setContentType(contentType);
if (headerMap != null && headerMap.size() > 0) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
}
HttpEntity entity = new HttpEntity(obj, headers);
ParameterizedTypeReference<List<T>> responseType = new ParameterizedTypeReference<List<T>>() {
};
ResponseEntity<List<T>> exchange = restTemplate.exchange(url, method, entity, responseType);
// RestTemplate Will List<obj> To List<LinkedHashMap>
List<T> list = exchange.getBody();
return mapToEntity(list, tClass);
}
public static <T> List<T> mapToEntity(List<T> body, Class<T> clazz) {
List<T> list = new ArrayList<>();
if (body.size() <= 0) {
return list;
}
List<Map<String, Object>> mapList = new ArrayList<>();
for (T t : body) {
Map<String, Object> map = (Map<String, Object>) t;
mapList.add(map);
}
try {
Field[] declaredFields = clazz.getDeclaredFields();
for (Map<String, Object> map : mapList) {
T t = clazz.newInstance();
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
String name = declaredField.getName();
if (null != map.get(name)) {
declaredField.set(t, map.get(name));
}
}
list.add(t);
}
} catch (Exception e) {
throw new RuntimeException(" Property setting failed !");
}
return list;
}
}
3、GET request
@RestController
public class Controller {
@RequestMapping("/test")
public String sendThymeleaf() {
// request URL( If you have parameters, you can encapsulate )
String url = "http://127.0.0.1:9898/other/test2?name= test &age=123";
// Package head
Map<String, String> headerMap = new HashMap<>();
headerMap.put("token", "123456");
// Set response entity , For example User, Then incoming User.class that will do
User user = fileRequestServer.doHttp(url, MediaType.APPLICATION_JSON, headerMap, HttpMethod.GET, null, User.class);
System.out.println(user.toString());
}
}
4、POST request
@RestController
public class Controller {
@RequestMapping("/test")
public String sendThymeleaf() {
String url = "http://127.0.0.1:9898/other/test2";
// POST When asked , The parameter can be Map Objects can also be concrete entity objects , A choice
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("name", " Test the name ");
paramMap.put("gender", " male ");
paramMap.put("age", 10);
// POST When asked , The parameter can be Map Objects can also be concrete entity objects , A choice
// UserParam param= new UserParam ();
// param.setName(" Test the name ");
// param.setgender(" male ");
// param.setAge(10);
// Package head
Map<String, String> headerMap = new HashMap<>();
headerMap.put("token", "123456");
// Set response entity , For example User, Then incoming User.class that will do
User user = fileRequestServer.doHttp(url, MediaType.APPLICATION_JSON, headerMap, HttpMethod.POST, paramMap, User.class);
System.out.println(user.toString());
}
}
5、PUT request
@RestController
public class Controller {
@RequestMapping("/test")
public String sendThymeleaf() {
String url = "http://127.0.0.1:9898/other/test2";
// PUT When asked , The parameter can be Map Objects can also be concrete entity objects , A choice
// Map<String, Object> paramMap = new HashMap<>();
// paramMap.put("name", " Test the name ");
// paramMap.put("gender", " male ");
// paramMap.put("age", 10);
// PUT When asked , The parameter can be Map Objects can also be concrete entity objects , A choice
UserParam param= new UserParam ();
param.setName(" Test the name ");
param.setgender(" male ");
param.setAge(10);
// Package head
Map<String, String> headerMap = new HashMap<>();
headerMap.put("token", "123456");
// Set response entity , For example User, Then incoming User.class that will do
User user = fileRequestServer.doHttp(url, MediaType.APPLICATION_JSON, headerMap, HttpMethod.PUT, param, User.class);
System.out.println(user.toString());
}
}
6、DELETE request
@RestController
public class Controller {
@RequestMapping("/test")
public String sendThymeleaf() {
// 123456 by DELETE Parameters at the time of request , such as :test2/{id}
String url = "http://127.0.0.1:9898/other/test2/123456";
// DELETE When asked , if necessary body Parameters , Then you can do it for Map Objects can also be concrete entity objects , A choice
// Map<String, Object> paramMap = new HashMap<>();
// paramMap.put("name", " Test the name ");
// paramMap.put("gender", " male ");
// paramMap.put("age", 10);
// DELETE When asked , if necessary body Parameters , Then you can do it for Map Objects can also be concrete entity objects , A choice
// UserParam param= new UserParam ();
// param.setName(" Test the name ");
// param.setgender(" male ");
// param.setAge(10);
// Package head
Map<String, String> headerMap = new HashMap<>();
headerMap.put("token", "123456");
// Set response entity , For example User, Then incoming User.class that will do
// DELETE If you don't need parameters , that obj Pass in null that will do , if necessary body Parameters pass response parameters
User user = fileRequestServer.doHttp(url, MediaType.APPLICATION_JSON, headerMap, HttpMethod.PUT, null, User.class);
System.out.println(user.toString());
}
}
7、List Collection response request
When the return object is a List when , Then use doHttpList() Method ;
@RestController
public class Controller {
@RequestMapping("/test")
public String sendThymeleaf() {
// request URL( If you have parameters, you can encapsulate )
String url = "http://127.0.0.1:9898/other/test2?name= test &age=123";
// Package head
Map<String, String> headerMap = new HashMap<>();
headerMap.put("token", "123456");
// Set response entity , For example User, Then incoming User.class that will do
List<User> user = fileRequestServer.doHttpList(url, MediaType.APPLICATION_JSON, headerMap, HttpMethod.GET, null, User.class);
System.out.println(user.toString());
}
}
8、 File transfer request ( Batch files are available 、 With parameters )
@RestController
public class Controller {
@PostMapping("/test")
public void test(@RequestParam("files") MultipartFile[] file) throws IOException {
String url = "http://127.0.0.1:9898/other/test";
// Upload files
String originalFilename = file.getOriginalFilename();
System.out.println(" File name :" + originalFilename);
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
// Traverse multiple MultipartFile object ;
for (MultipartFile file : files) {
ByteArrayResource resource = new ByteArrayResource(file.getBytes()) {
@Override
public String getFilename() {
return file.getOriginalFilename();
}
};
// Write file stream : Each time , Just add once
paramMap.add("files", resource);
}
// The other parameters
paramMap.add("name", " Test the name ");
paramMap.add("age", 10);
// Package head
Map<String, String> headerMap = new HashMap<>();
headerMap.put("token", "12333");
String s = fileRequestServer.doHttp(url, MediaType.MULTIPART_FORM_DATA, headerMap, HttpMethod.POST, paramMap, String.class);
System.out.println(s);
}
}
Called party Controller Layer definition :
If you pass in the file stream at the same time , If there are still parameters , Then participation requires the use of @RequestParam Define ;
public String test(@RequestParam("files") MultipartFile[] file, @RequestParam String name, @RequestParam Integer age){
......
......
}
边栏推荐
- 函数名指针和函数指针
- 【Cadence Allegro PCB设计】error: Possible pin type conflict GND/VCC Power Connected to Output
- 哈夫曼树的构建
- Wu Enda logistic regression 2
- Summary of 80 domestic database operation documents (including tidb, Damon, opengauss, etc.)
- 理财有保本产品吗?
- 「数字安全」警惕 NFT的七大骗局
- Methods of de duplication and connection query in MySQL database
- 咨询下flink sql-client怎么处理DDL后,fink sql里面映射表加字段以及JOb?
- 01. Sum of two numbers
猜你喜欢

Interviewer: talk about log The difference between fatal and panic

How to fix the first row title when scrolling down in Excel table / WPS table?

我也是醉了,Eureka 延迟注册还有这个坑!

带你初步了解多方安全计算(MPC)

POWERBOARD coco! Dino: let target detection embrace transformer

Three dimensional function display of gray image

论文阅读_多任务学习_MMoE

Starting from business needs, open the road of efficient IDC operation and maintenance

一篇文章了解超声波加湿器

Redis源码与设计剖析 -- 17.Redis事件处理
随机推荐
Redis源码与设计剖析 -- 15.RDB持久化机制
An article about ultrasonic humidifier
I2C communication - sequence diagram
Is it safe to open a futures account online? How to apply for a low handling fee?
电子产品“使用”和“放置”哪个寿命更长??
Idea essential plug-ins
实时黄金交易平台哪个可靠安全?
Highlights
PostgreSQL里有只编译语句但不执行的方法吗?
[vscode] support argparser/ accept command line parameters
Is there a method in PostgreSQL that only compiles statements but does not execute them?
Installation steps and usage of NVM under windows10 system
[solution] the Microsoft edge browser has the problem of "unable to access this page"
POWERBOARD coco! Dino: let target detection embrace transformer
Redis源码与设计剖析 -- 16.AOF持久化机制
爬虫框架-crawler
Boring post roast about work and life
Starting from business needs, open the road of efficient IDC operation and maintenance
P2P 之 UDP穿透NAT的原理与实现
11. Camera and lens