Webflux WebClient请求日志和响应只能获取一次处理

废话不多说,直接上代码

    @Bean
    public WebClient webClient(){
        return WebClient.builder().filter((request, next) -> {
            String prefix = request.logPrefix();
            log.info("{}请求地址为:{} {}", prefix, request.method(), request.url());
            log.info("{}请求Header为:{}", prefix, JsonUtils.stringify(request.headers()));
            String body = parserBody(request.body());
            if (body != null){
                log.info("{}请求体:{}", prefix, body);
            }
            return next.exchange(request)
                    .flatMap(clientResponse -> clientResponse.bodyToMono(String.class)
                            .map(resp -> {
                                log.info("{}请求响应为(Map):{}", prefix, resp);
                   // 响应已获取,无法重新获取 需要生成新的响应
return ClientResponse .create(clientResponse.statusCode()) .body(resp) .headers(httpHeaders -> httpHeaders.addAll(clientResponse.headers().asHttpHeaders())) .cookies(cookie -> cookie.addAll(clientResponse.cookies())) .statusCode(clientResponse.statusCode()) .build(); }) ) ; }).build(); } @SuppressWarnings(value = {"java:S3011"}) public String parserBody(BodyInserter<?, ? super ClientHttpRequest> bodyInserter){ //noinspection rawtypes Class<? extends BodyInserter> clazz = bodyInserter.getClass(); Field data; try { data = clazz.getDeclaredField("data"); data.setAccessible(true); Object result = data.get(bodyInserter); data.setAccessible(false); return JsonUtils.stringify(result); } catch (Exception e) { // ignore error } return null; }

 

posted on 2022-07-06 09:21  假想丿殇  阅读(699)  评论(2编辑  收藏  举报

导航