SpringBoot RestTemplate请求日志打印方式
作者:Yweir
这篇文章主要介绍了SpringBoot RestTemplate请求日志打印方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
SpringBoot RestTemplate请求日志打印
RestTemplateConfig 配置
@Configuration public class RestTemplateConfig { /** * 初始化连接工厂 * @return */ @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory(){ SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); /**连接超时*/ factory.setConnectTimeout(15000); /**读超时*/ factory.setReadTimeout(5000); return factory; } /** * 初始化请求模板 * @param simpleClientHttpRequestFactory * @return */ @Bean public RestTemplate restTemplate(ClientHttpRequestFactory simpleClientHttpRequestFactory,@Qualifier("loggingRequestInterceptor") LoggingRequestInterceptor loggingRequestInterceptor){ RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(simpleClientHttpRequestFactory)); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(loggingRequestInterceptor); restTemplate.setInterceptors(interceptors); return restTemplate; } /** * 返回请求工具类 * @param restTemplate * @return */ @Bean public HttpRequestUtils getHttpRequestUtils(RestTemplate restTemplate){ HttpRequestUtils httpRequestUtils = new HttpRequestUtils(); httpRequestUtils.setRestTemplate(restTemplate); return httpRequestUtils; } }
HttpUtils 工具类
public class HttpUtils { private RestTemplate restTemplate; public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } /** * @param : url * @description: post请求 get */ public String sendGetRequest(String url) throws IOException { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity httpEntity = new HttpEntity(headers);//请求体,包括请求数据 body 和 请求头 headers ResponseEntity<String> strbody = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class); return strbody.getBody(); } /** * @param : url * @param : data * @description: post请求 json */ public String sendPostRequest(String url, JSONObject data) throws IOException { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity httpEntity = new HttpEntity(data, headers);//请求体,包括请求数据 body 和 请求头 headers ResponseEntity<String> strbody = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class); return strbody.getBody(); } /** * @param : url * @param : data * @description: post请求 json */ public String sendPostRequest(String url, String data) throws IOException { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity httpEntity = new HttpEntity(data, headers);//请求体,包括请求数据 body 和 请求头 headers ResponseEntity<String> strbody = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class); return strbody.getBody(); } }
LoggingRequestInterceptor 拦截类
@Component("loggingRequestInterceptor") public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor { Logger log = LoggerFactory.getLogger(getClass()); @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) throws IOException { 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, "UTF-8")); log.debug("==========================request end================================================"); } private void traceResponse(ClientHttpResponse response) throws IOException { StringBuilder inputStringBuilder = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "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.toString()); log.debug("=======================response end================================================="); } }
关于springboot restTemplate传文件爬坑
关于restTemplate post请求中包含文件类型
public void test5(){ MultiValueMap param = new LinkedMultiValueMap(); FileSystemResource file = new FileSystemResource("C:\\Users\\Ryan\\Postman\\files\\zm.png"); param .add("image",file); ResponseEntity<String> idCardOcrRes = this.restTemplateForFile(idCardOCRUrl,param,String.class); String idCardOcrResBody = idCardOcrRes.getBody(); System.out.println(idCardOcrResBody); } private <T> ResponseEntity<T> restTemplateForFile(String url, MultiValueMap<String,Object> map, Class<T> responseClass){ //设置请求头 HttpHeaders headers = new HttpHeaders(); MediaType mediaType = MediaType.parseMediaType("multipart/form-data"); headers.setContentType(mediaType); //请求体为入参map //用httpEntity封装整个请求报文 HttpEntity<MultiValueMap<String,Object>> entity = new HttpEntity(map,headers); ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, entity, responseClass); return responseEntity; }
注意使用FileSystemResource类型的文件即可。
本人在过程中遇到过一个问题,在此记录下来,param为MultiValueMap
logger.info("param:{},userNo:{},incomingNo:{}",JSONObject.toJSONString(param),userNo,incomingNo);
若加入此日志输出,会清空新建的文件,这个问题困扰好久!!!
关于restTemplate 响应状态码捕捉
捕捉 RestClientResponseException e 类型异常,
int statis = e.getRawStatusCode(); String responseBodyAsString = e.getResponseBodyAsString();
可以得到具体的响应消息以及响应状态码
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。