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();

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

总结

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

相关文章

  • Java实现登录密码强度校验的项目实践

    Java实现登录密码强度校验的项目实践

    本文主要介绍了Java实现登录密码强度校验的项目实践,包括使用正则表达式匹配校验和密码强度校验工具类这两种方法,具有一定的参考价值,感兴趣的可以了解一下
    2024-01-01
  • 简单了解Spring Bean常用注解的装配

    简单了解Spring Bean常用注解的装配

    这篇文章主要介绍了简单了解Spring Bean常用注解的装配,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • SpringBoot对接twilio实现邮件信息发送功能

    SpringBoot对接twilio实现邮件信息发送功能

    这篇文章主要为大家详细介绍了SpringBoot如何对接twilio实现邮件信息发送功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2025-03-03
  • java基础之泛型知识点总结

    java基础之泛型知识点总结

    这篇文章主要介绍了java基础之泛型知识点总结,文中有非常详细的代码示例,对正在学习java基础的小伙伴们有很好的帮助,需要的朋友可以参考下
    2021-04-04
  • SpringBoot模拟员工数据库并实现增删改查操作

    SpringBoot模拟员工数据库并实现增删改查操作

    这篇文章主要给大家介绍了关于SpringBoot模拟员工数据库并实现增删改查操作的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2021-09-09
  • java中接口和事件监听器的深入理解

    java中接口和事件监听器的深入理解

    这篇文章主要给大家介绍了关于java中接口和事件监听器的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用java具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-12-12
  • 分析ABA问题的本质及其解决办法

    分析ABA问题的本质及其解决办法

    CAS的全称是compare and swap,它是java同步类的基础,java.util.concurrent中的同步类基本上都是使用CAS来实现其原子性的。本文将介绍ABA问题的本质及其解决办法。
    2021-06-06
  • IDEA中application.properties的图标显示不正常的问题及解决方法

    IDEA中application.properties的图标显示不正常的问题及解决方法

    这篇文章主要介绍了IDEA中application.properties的图标显示不正常的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-04-04
  • Springboot项目的服务器部署与发布方式

    Springboot项目的服务器部署与发布方式

    本文记录了将Springboot项目部署到服务器并发布的过程,包括在IDEA中打包、选择服务器、连接服务器、安装环境、上传jar包、配置环境变量以及运行项目等步骤
    2025-03-03
  • 深入理解Java中的克隆

    深入理解Java中的克隆

    想必大家对克隆都有耳闻,世界上第一只克隆羊多莉就是利用细胞核移植技术将哺乳动物的成年体细胞培育出新个体,甚为神奇。其实在Java中也存在克隆的概念,即实现对象的复制。本文将尝试介绍一些关于Java中的克隆和一些深入的问题,希望可以帮助大家更好地了解克隆。
    2016-08-08

最新评论