SpringBoot RestTemplate请求日志打印方式

 更新时间:2023年07月07日 09:41:00   作者: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();

可以得到具体的响应消息以及响应状态码

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • BigDecimal divide除法除不尽报错的问题及解决

    BigDecimal divide除法除不尽报错的问题及解决

    这篇文章主要介绍了BigDecimal divide除法除不尽报错的问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • 浅谈Java ThreadPoolExecutor的使用

    浅谈Java ThreadPoolExecutor的使用

    今天我们来学习一下Java ThreadPoolExecutor的使用,文中有非常详细的介绍及代码示例,对正在学习Java的小伙伴们有很大的帮助,需要的朋友可以参考下
    2021-05-05
  • IntelliJ IDEA 2021.3 正式发布之支持远程开发、IDE故障排查等多项优化改进

    IntelliJ IDEA 2021.3 正式发布之支持远程开发、IDE故障排查等多项优化改进

    IntelliJ IDEA 2021.3 正式发布:支持远程开发、IDE故障排查等多项优化改进问题,在这个版本中的远程开发还不是一个正式版本,而是BETA版,但通过这个BETA版本,也可以体验IDEA“远程开发”给我们带来的全新体验
    2021-12-12
  • Java后端用EL表达式改进JSP

    Java后端用EL表达式改进JSP

    EL 全名为Expression Language,EL的语法很简单,它最大的特点就是使用上很方便,本文带你用EL表达式改进JSP,感兴趣的朋友来看看吧
    2022-02-02
  • 浅谈Action+Service +Dao 功能

    浅谈Action+Service +Dao 功能

    下面小编就为大家带来一篇浅谈Action+Service +Dao 功能。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-07-07
  • Spring Boot报错:No session repository could be auto-configured, check your configuration的解决方法

    Spring Boot报错:No session repository could be auto-configured

    这篇文章主要给大家介绍了关于Spring Boot报错:No session repository could be auto-configured, check your configuration的解决方法,文中给出了详细的解决方法,对遇到这个问题的朋友们具有一定参考价值,需要的朋友下面来一起看看吧。
    2017-07-07
  • java实现注册登录系统

    java实现注册登录系统

    这篇文章主要为大家详细介绍了java实现注册登录系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-04-04
  • Dubbo在Spring和Spring Boot中的使用详解

    Dubbo在Spring和Spring Boot中的使用详解

    这篇文章主要介绍了Dubbo在Spring和Spring Boot中的使用详解,需要的朋友可以参考下
    2017-10-10
  • SSH框架网上商城项目第11战之查询和删除商品功能实现

    SSH框架网上商城项目第11战之查询和删除商品功能实现

    这篇文章主要为大家详细介绍了SSH框架网上商城项目第11战之查询和删除商品功能实现的相关资料,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-06-06
  • 详解在SpringBoot中@Transactional事物操作和事物无效问题排查

    详解在SpringBoot中@Transactional事物操作和事物无效问题排查

    这篇文章主要介绍了详解在SpringBoot中@Transactional事物操作和事物无效问题排查,本文详细的介绍了SpringBoot中集成使用@Transactional注解操作事物以及事物开启后无效的问题排查,需要的朋友可以参考下
    2021-06-06

最新评论