国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

java打印http接口的請求和響應(yīng)

這篇具有很好參考價(jià)值的文章主要介紹了java打印http接口的請求和響應(yīng)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

打印http接口的請求和響應(yīng)

一、簡述

基于spring提供的機(jī)制,有3種方法可以實(shí)現(xiàn)接口請求響應(yīng)日志的打印,分別是CommonsRequestLoggingFilter、HandlerInterceptor、RequestBodyAdviceAdapter、ResponseBodyAdvice。

二、修改日志級別打印請求參數(shù)

通過設(shè)置 web 的日志級別為 DEBUG,spring會自己打印請求參數(shù)。該方法打印的內(nèi)容覆蓋了后面介紹的所有方法中日志的內(nèi)容,如果不需要做定制打印,并且不介意打印的日志級別是DEBUG,那就足夠用了。

logging:
  level:
    root: INFO
    web: DEBUG

三、使用 CommonsRequestLoggingFilter 打印請求參數(shù)

CommonsRequestLoggingFilter的使用比較簡單,只需要實(shí)現(xiàn)一個logFilter的bean即可。
只不過logFilter的日志級別是debug,需要在日志配置文件中,將CommonsRequestLoggingFilter類的日志級別設(shè)置為debug級別。
同時在生產(chǎn)環(huán)境的日志文件中打印debug日志不符合規(guī)范。

@Bean
public CommonsRequestLoggingFilter logFilter() {
    CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();

    loggingFilter.setIncludeQueryString(true);
    loggingFilter.setIncludePayload(true);
    loggingFilter.setMaxPayloadLength(2048);

    return loggingFilter;
}

四、使用 HandlerInterceptor 打印請求參數(shù)

HandlerInterceptor 可以獲取到接口執(zhí)行過程中的 HttpServletRequest 和 HttpServletResponse 信息,因此能夠打印出接口請求響應(yīng)內(nèi)容。

@Component
public class LogInterceptorAdapter extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {

        ServletRequest servletRequest = new ContentCachingRequestWrapper(request);
        Map<String, String[]> params = servletRequest.getParameterMap();

        // 從 request 中讀取請求參數(shù)并打印
        params.forEach((key, value) -> log.info("logInterceptor " + key + "=" + Arrays.toString(value)));
        // 避免從 inputStream 中讀取body并打印

        return true;
    }
}

這種方式有個缺陷,對于 application/json 這種請求參數(shù)放在body中的方式,需要通過InputStream讀取內(nèi)容,而InputStream只能被讀取一次,
一旦在 HandlerInterceptor 中進(jìn)行了 InputStream 的讀取操作,后續(xù)的處理就讀取不到InputStream中的內(nèi)容,這是一個很嚴(yán)重的問題。
因此 HandlerInterceptor 不能用于打印請求中的body,可以改造一下該方法,只打印get請求參數(shù),post的請求參數(shù)用下面介紹的 RequestBodyAdviceAdapter 方法打印。

@Slf4j
@Component
public class LogInterceptorAdapter extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        if (DispatcherType.REQUEST.name().equals(request.getDispatcherType().name())
                && request.getMethod().equals(HttpMethod.GET.name())) {

            ServletRequest servletRequest = new ContentCachingRequestWrapper(request);
            Map<String, String[]> params = servletRequest.getParameterMap();

            // 從 request 中讀取請求參數(shù)并打印
            params.forEach((key, value) -> log.info("logInterceptor " + key + "=" + Arrays.toString(value)));
            // 避免從 inputStream 中讀取body并打印

        }
        return true;
    }
}

五、使用 RequestBodyAdviceAdapter 打印請求參數(shù)

RequestBodyAdviceAdapter 封裝了 afterBodyRead 方法,在這個方法中可以通過 Object body 參數(shù)獲取到body的內(nèi)容。

@ControllerAdvice
public class CustomRequestBodyAdviceAdapter extends RequestBodyAdviceAdapter {

    @Autowired
    HttpServletRequest httpServletRequest;

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, 
                            Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage,
                                MethodParameter parameter, Type targetType,
            Class<? extends HttpMessageConverter<?>> converterType) {

        // 打印body內(nèi)容

        return super.afterBodyRead(body, inputMessage, parameter, targetType, converterType);
    }
}

六、使用 ResponseBodyAdvice 打印響應(yīng)內(nèi)容

ResponseBodyAdvice 和 RequestBodyAdviceAdapter 同屬于 ControllerAdvice。ResponseBodyAdvice 封裝了 beforeBodyWrite 方法,可以獲取到響應(yīng)報(bào)文。

@ControllerAdvice
public class CustomResponseBodyAdviceAdapter implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter,
                            Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {

        if (serverHttpRequest instanceof ServletServerHttpRequest &&
                serverHttpResponse instanceof ServletServerHttpResponse) {
            // 打印響應(yīng)body
        }

        return body;
    }
}

七、使用 filter 打印請求和響應(yīng)

通過繼承spring的 OncePerRequestFilter實(shí)現(xiàn)自定義filter。在filter中讀取請求和響應(yīng)的body需要做一下特殊處理,因?yàn)榱髦荒鼙蛔x取一次,在filter中被讀取了,后續(xù)的處理就無法再次讀取流的內(nèi)容了。

spring提供了 ContentCachingRequestWrapper和 ContentCachingResponseWrapper兩個類來解決這個問題。

@Slf4j
@Component
public class AccessLogFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        ContentCachingRequestWrapper req = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper resp = new ContentCachingResponseWrapper(response);

        try {
            // Execution request chain
            filterChain.doFilter(req, resp);
            // Get body
            byte[] requestBody = req.getContentAsByteArray();
            byte[] responseBody = resp.getContentAsByteArray();
        
            log.info("request body = {}", new String(requestBody, StandardCharsets.UTF_8));
            log.info("response body = {}", new String(responseBody, StandardCharsets.UTF_8));
        } finally {
        // Finally remember to respond to the client with the cached data.
            resp.copyBodyToResponse();
        }    
    }
}

原文鏈接:https://blog.csdn.net/haiyan_qi/article/details/109960325文章來源地址http://www.zghlxwxcb.cn/news/detail-787573.html

到了這里,關(guān)于java打印http接口的請求和響應(yīng)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Java接口通用請求和響應(yīng)

    2024年02月15日
    瀏覽(18)
  • Java課題筆記~ HTTP協(xié)議(請求和響應(yīng))

    Java課題筆記~ HTTP協(xié)議(請求和響應(yīng))

    Servlet最主要的作用就是處理客戶端請求,并向客戶端做出響應(yīng)。為此,針對Servlet的每次請求,Web服務(wù)器在調(diào)用service()方法之前,都會創(chuàng)建兩個對象 分別是HttpServletRequest和HttpServletResponse。 其中HttpServletRequest用于封裝HTTP請求消息,簡稱request對象; HttpServletResponse用于封裝HTT

    2024年02月13日
    瀏覽(22)
  • Java Restful API接口獲取請求頭、請求體、以及設(shè)置響應(yīng)狀態(tài)碼、應(yīng)答(響應(yīng))體等

    一、獲取請求頭 接口示例1: 1、從 request?對象中獲取請求頭: 二、獲取請求體 1、從 request?對象中,使用緩沖流讀取器、stream流等方式獲取請求體 推薦寫法一:

    2024年02月16日
    瀏覽(42)
  • Java http 接口請求

    2024年02月11日
    瀏覽(21)
  • log4j控制臺不打印日志的故障解決方案

    log4j控制臺不打印日志的故障解決方案

    接管了別的項(xiàng)目組的一個代碼,在IDAE調(diào)試程序的過程中,發(fā)現(xiàn)log4j日志居然沒有打印在控制臺上,日志相關(guān)代碼也沒有問題。 在網(wǎng)上搜索了一圈,總結(jié)了一下個人解決這個問題的流程。 1. 判斷用了什么配置文件 不知道是出于什么目的,項(xiàng)目中居然有l(wèi)og4j的properties和xml兩個配

    2024年02月04日
    瀏覽(138)
  • (下篇)java通過http請求請求三方接口:設(shè)置請求頭,請求體

    (下篇)java通過http請求請求三方接口:設(shè)置請求頭,請求體

    介紹:springcloud項(xiàng)目server子模塊內(nèi)部集成了低代碼平臺來配置通用列表查詢,需要對低代碼配置權(quán)限,低代碼使用不了server模塊的feign調(diào)用,只能用http請求去調(diào)用分布式項(xiàng)目的用戶模塊來獲取權(quán)限,通過restTemplate調(diào)用接口,postman攜帶token信息可以直接調(diào)通用戶中心,但是通過

    2024年02月04日
    瀏覽(19)
  • java調(diào)用http接口(get請求和post請求)

    1.http接口的格式如下: 圖片選擇失敗,我只能把數(shù)據(jù)貼出來,如果有不懂的可以問我哈。 http://localhost:8881/department/getDepartmentList接口數(shù)據(jù)如下:(請求方式是GET) http://localhost:8881/department/getDataById?id=3接口數(shù)據(jù)如下:(請求方式是POST) 2.需要引入的包有: 3.實(shí)現(xiàn)方法如下:

    2024年02月13日
    瀏覽(25)
  • SpringCloud Gateway 打印請求響應(yīng)日志

    SpringCloud Gateway 打印請求響應(yīng)日志

    version spring-cloud 2021.0.1 spring-boot 2.6.3 spring-cloud-alibaba 2021.0.1.0 網(wǎng)關(guān)不是基于springmvc的,而是基于webflux去做的 SpringCloudGateway中Post請求參數(shù)只能讀取一次 這是因?yàn)镚ateway默認(rèn)使用的是SpringWebflux,解決這個問題需要容重新構(gòu)造一個request來替換原先的request CacheBodyGlobalFilter這個全局過

    2024年02月02日
    瀏覽(97)
  • Java請求Http接口-OkHttp(超詳細(xì)-附帶工具類)

    Java請求Http接口-OkHttp(超詳細(xì)-附帶工具類)

    簡介:OkHttp是一個默認(rèn)有效的HTTP客戶端,有效地執(zhí)行HTTP可以加快您的負(fù)載并節(jié)省帶寬,如果您的服務(wù)有多個IP地址,如果第一次連接失敗,OkHttp將嘗試備用地址。這對于IPv4 + IPv6和冗余數(shù)據(jù)中心中托管的服務(wù)是必需的。OkHttp啟動具有現(xiàn)代TLS功能(SNI,ALPN)的新連接,并在握手

    2024年02月12日
    瀏覽(32)
  • java的amazonaws接口出現(xiàn)無法執(zhí)行http請求:管道中斷

    java使用amazonaws的接口上傳文件到minio出現(xiàn)以下異常: com.amazonaws.SdkClientException: Unable to execute HTTP request: Broken pipe (Write failed) at com.amazonaws.http.AmazonHttpClient R e q u e s t E x e c u t o r . h a n d l e R e t r y a b l e E x c e p t i o n ( A m a z o n H t t p C l i e n t . j a v a : 1175 ) a t c o m . a m a z o n a

    2024年02月07日
    瀏覽(34)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包