package com.util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Configuration
public class RestTemplateUtils {
private static final int DEFAULT_TIMEOUT = 5000;
private static RestTemplate instanceRestTemplate;
@Bean("restTemplate")
public RestTemplate restTemplate() {
instanceRestTemplate = getInstance();
return instanceRestTemplate;
}
public static RestTemplate getInstance() {
return getRestTemplateByTimeout(DEFAULT_TIMEOUT);
}
public static RestTemplate getRestTemplateByTimeout(int timeout) {
return getRestTemplateByTimeout(timeout, timeout);
}
public static RestTemplate getRestTemplateByTimeout(int connectTimeout, int readTimeout) {
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectionRequestTimeout(connectTimeout);
httpRequestFactory.setConnectTimeout(connectTimeout);
httpRequestFactory.setReadTimeout(readTimeout);
RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();
httpMessageConverters.forEach(httpMessageConverter -> {
if (httpMessageConverter instanceof StringHttpMessageConverter) {
StringHttpMessageConverter messageConverter = (StringHttpMessageConverter)httpMessageConverter;
messageConverter.setDefaultCharset(StandardCharsets.UTF_8);
}
});
restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler());
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new LoggingRequestInterceptor());
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
/**
* 无参数方式post
*
* @param restTemplate
* @param url
* @param clazz
* @param
* @return
*/
public static <T> T post(RestTemplate restTemplate, String url, Class<T> clazz) {
return post(restTemplate, url, null, null, null, clazz);
}
/**
* 只有query参数方式post
*
* @param restTemplate
* @param url
* @param queryParamMap
* @param clazz
* @param
* @return
*/
public static <T> T post(RestTemplate restTemplate, String url, LinkedMultiValueMap<String, String> queryParamMap, Class<T> clazz) {
return post(restTemplate, url, null, queryParamMap, null, clazz);
}
/**
* body参数方式post
*
* @param restTemplate
* @param url
* @param body
* @param clazz
* @param
* @return
*/
public static <T> T post(RestTemplate restTemplate, String url, Object body, Class<T> clazz) {
return post(restTemplate, url, body, null, null, clazz);
}
/**
* body header参数方式post
*
* @param restTemplate
* @param url
* @param body
* @param httpHeaders
* @param clazz
* @param
* @return
*/
public static <T> T post(RestTemplate restTemplate, String url, Object body, HttpHeaders httpHeaders, Class<T> clazz) {
return post(restTemplate, url, body, null, httpHeaders, clazz);
}
/**
* 文件方式
*
* @param restTemplate
* @param url
* @param map
* @param clazz
* @param
* @return
*/
public static <T> T postFile(RestTemplate restTemplate, String url, LinkedMultiValueMap<String, Object> map, Class<T> clazz) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
return postFile(restTemplate, url, map, headers, clazz);
}
/**
* 可带query参数
*
* @param restTemplate
* @param url
* @param body
* @param queryParamMap query参数
* @param headers
* @param clazz
* @param
* @return
* @param
*/
public static <T, E> T post(RestTemplate restTemplate, String url, E body, LinkedMultiValueMap<String, String> queryParamMap, HttpHeaders headers, Class<T> clazz) {
String requestUrl = url;
if (MapUtils.isNotEmpty(queryParamMap)) {
requestUrl = UriComponentsBuilder.fromUriString(url).queryParams(queryParamMap).build().encode(StandardCharsets.UTF_8).toUriString();
}
if (null == headers) {
headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
}
HttpEntity<E> entity = new HttpEntity<>(body, headers);
ResponseEntity<T> exchange = exchangePost(restTemplate, requestUrl, entity, clazz);
return exchange.getBody();
}
/**
* 文件方式FileSystemResource
*
* @param restTemplate
* @param url
* @param map
* @param headers
* @param clazz
* @param
* @return
*/
public static <T> T postFile(RestTemplate restTemplate, String url, LinkedMultiValueMap<String, Object> map, HttpHeaders headers, Class<T> clazz) {
if (null == headers) {
headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
}
HttpEntity<LinkedMultiValueMap<String, Object>> entity = new HttpEntity<>(map, headers);
ResponseEntity<T> exchange = exchangePost(restTemplate, url, entity, clazz);
return exchange.getBody();
}
private static <E, T> ResponseEntity<T> exchangePost(RestTemplate restTemplate, String requestUrl, HttpEntity<E> entity, Class<T> targetClazz) {
RestTemplate restTemplate$;
if (null == restTemplate) {
restTemplate$ = instanceRestTemplate;
} else {
restTemplate$ = restTemplate;
}
return restTemplate$.exchange(requestUrl, HttpMethod.POST, entity, targetClazz);
}
}
@Slf4j
public class RestTemplateResponseErrorHandler extends DefaultResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
}
第二个类:
@Slf4j
public class LoggingRequestInterceptor 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) {
if (log.isDebugEnabled()) {
log.debug("===========================request begin================================================");
log.debug("URI : {}", request.getURI());
log.debug("Method : {}", request.getMethod());
log.debug("Headers : {}", request.getHeaders());
log.debug("Request body: {}", new String(body, StandardCharsets.UTF_8));
log.debug("==========================request end================================================");
}
}
private void traceResponse(ClientHttpResponse response) throws IOException {
if (log.isDebugEnabled()) {
StringBuilder inputStringBuilder = new StringBuilder();
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();
}
log.debug("============================response begin==========================================");
log.debug("Status code : {}", response.getStatusCode());
log.debug("Status text : {}", response.getStatusText());
log.debug("Headers : {}", response.getHeaders());
log.debug("Response body: {}", inputStringBuilder);
log.debug("=======================response end=================================================");
}
}
}
String url = "www.baidu.com";
String thirdResult = RestTemplateUtils.post(null, url , dto, String.class);