gpt4 book ai didi

spring-boot - Spring Boot 2 Actuator (2.0.1-RELEASE) - 请求和响应主体

转载 作者:行者123 更新时间:2023-12-03 16:40:53 24 4
gpt4 key购买 nike

关注帖子 post创建过滤器以获取请求和响应正文。

Spring Boot 2 过滤器 (HttpTraceFilter) 似乎有点不同,所以不确定如何从请求属性设置 http 跟踪属性。

非常感谢任何帮助!

@Component
public class RequestTraceFilter extends HttpTraceFilter {

/**
* Create a new {@link HttpTraceFilter} instance.
*
* @param repository the trace repository
* @param tracer used to trace exchanges
*/
public RequestTraceFilter(HttpTraceRepository repository,
HttpExchangeTracer tracer) {
super(repository, tracer);
}

//TODO override the filter :(
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws
ServletException,
IOException {

ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);

filterChain.doFilter(requestWrapper, responseWrapper);
responseWrapper.copyBodyToResponse();
request.setAttribute("REQUEST_BODY", getRequestBody(requestWrapper));
request.setAttribute("RESPONSE_BODY", getResponseBody(responseWrapper));

super.doFilterInternal(requestWrapper, responseWrapper, filterChain);

}

private String getRequestBody(ContentCachingRequestWrapper request) {
ContentCachingRequestWrapper wrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
String characterEncoding = wrapper.getCharacterEncoding();
return getPayload(wrapper.getContentAsByteArray(), characterEncoding);
}

private String getResponseBody(ContentCachingResponseWrapper response) {
ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
return getPayload(wrapper.getContentAsByteArray(), wrapper.getCharacterEncoding());
}

public String getPayload(byte[] buf, String characterEncoding) {
String payload = null;
if (buf.length > 0) {
try {
payload = new String(buf, 0, buf.length, characterEncoding);
}
catch (UnsupportedEncodingException ex) {
payload = "[unknown]";
}
}
return payload;
}

}

最佳答案

在 github 中收到了来自 wilkinsona 的回复:

https://github.com/spring-projects/spring-boot/issues/12953

2.0 中的 HTTP 跟踪故意不如 1.5 中的灵活。 1.5 中实现的灵活性导致了许多问题,并使其无法支持 WebFlux、Spring MVC 和 Jersey。从未支持开箱即用地跟踪请求和响应正文。不再支持跟踪参数,因为当请求是 POST 表单数据时,它需要读取整个请求正文。如果您想捕获其中一个或两个,我建议您不要,您应该实现自己的端点。

关于spring-boot - Spring Boot 2 Actuator (2.0.1-RELEASE) - 请求和响应主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49991723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com