当前位置:网站首页>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){
......
......
}
边栏推荐
- [Hardware Engineer] about signal level driving capability
- What financial products can you buy to make money with only 1000 yuan?
- 无聊发文吐槽工作生活
- [PHP pseudo protocol] source code reading, file reading and writing, and arbitrary PHP command execution
- 11. Camera and lens
- 【无标题】
- Summary of 80 domestic database operation documents (including tidb, Damon, opengauss, etc.)
- postgreSQL 密码区分大小写 ,有参数控制吗?
- PHP解决并发问题的几种实现
- Three dimensional function display of gray image
猜你喜欢
随机推荐
Idea essential plug-ins
I2C communication - sequence diagram
咨询下flink sql-client怎么处理DDL后,fink sql里面映射表加字段以及JOb?
Mongodb cluster and sharding
【Cadence Allegro PCB设计】永久修改快捷键(自定义)~亲测有效~
[cadence Allegro PCB design] permanently modify the shortcut key (customized) ~ it is valid for personal test~
Food safety | eight questions and eight answers take you to know crayfish again! This is the right way to eat!
go channel简单笔记
"Digital security" alert NFT's seven Scams
电子产品“使用”和“放置”哪个寿命更长??
STM32 PAJ7620U2手势识别模块(IIC通信)程序源码详解
RedisTemplate解决高并发下秒杀系统库存超卖方案 — Redis事务+乐观锁机制
我也是醉了,Eureka 延迟注册还有这个坑!
Pymongo saves data in dataframe format (insert_one, insert_many, multi-threaded saving)
栈的顺序存储结构,链式存储结构及实现
03.无重复字符的最长子串
走马卒
我也是醉了,Eureka 延迟注册还有这个坑!
[untitled]
postgreSQL 密码区分大小写 ,有参数控制吗?







