将有效负载获取到Rest端点

时间:2019-05-24 13:11:11

标签: java spring spring-boot spring-rest

我想使用此代码获取请求和响应有效负载:

https://gist.github.com/baberali/59ad73b2a1dcc5042e53f32585770df7

我尝试过:

@RestController()
public class HomeController {

    @PostMapping(value = "/v1")
    public Response handleMessage(@RequestBody Transaction transaction, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        HttpServletRequest requestToCache = new ContentCachingRequestWrapper(request);
        HttpServletResponse responseToCache = new ContentCachingResponseWrapper(response);

        String requestData = getRequestData(requestToCache);
        String responseData = getResponseData(responseToCache);
    }

    private static String getRequestData(final HttpServletRequest request) throws UnsupportedEncodingException {
        String payload = null;
        ContentCachingRequestWrapper wrapper = WebUtils.getNativeRequest(request,
                ContentCachingRequestWrapper.class);
        if (wrapper != null) {
            byte[] buf = wrapper.getContentAsByteArray();
            if (buf.length > 0) {
                payload = new String(buf, 0, buf.length, wrapper.getCharacterEncoding());
            }
        }
        return payload;
    }

    private static String getResponseData(final HttpServletResponse response) throws IOException {
        String payload = null;
        ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response,
                ContentCachingResponseWrapper.class);
        if (wrapper != null) {
            byte[] buf = wrapper.getContentAsByteArray();
            if (buf.length > 0) {
                payload = new String(buf, 0, buf.length, wrapper.getCharacterEncoding());
                wrapper.copyBodyToResponse();
            }
        }
        return payload;
    }
}

但是当我打印结果时,我得到NULL。你知道为什么内容为空吗?

1 个答案:

答案 0 :(得分:1)

您提供的示例中的代码可以用作过滤器(假设响应已编写)。 您正在使用控制器方法。在控制器中,您将能够获取请求。但是,响应是您需要编写但不需要阅读的东西。 将此逻辑移到过滤器链上。

在控制器方法中读取请求主体的代码:

@RestController()
public class HomeController {

    @PostMapping(value = "/v1")
    public Response handleMessage(@RequestBody String plainBody) throws Exception {

        System.out.println("This is request body: " + plainBody);
    }
}