Получить полезную нагрузку в конечную точку отдыха - PullRequest
0 голосов
/ 24 мая 2019

Я хочу использовать этот код для получения полезных данных запроса и ответа:

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 Ответ

1 голос
/ 24 мая 2019

Код в предоставленном вами примере работает как фильтр (при условии, что ответ уже написан).Вы используете метод контроллера.В контроллере вы сможете получить запрос.Но ответ - это то, что нужно написать, а не прочитатьПереместите эту логику в цепочку фильтров.

Код для чтения тела запроса в методе контроллера:

@RestController()
public class HomeController {

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

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