Журнал запросов и ответов в Spring API - PullRequest
0 голосов
/ 22 мая 2019

Я хочу реализовать Rest logging для API, используя Spring. Я попробовал это:

public static String readPayload(final HttpServletRequest request) throws IOException {
      String payloadData = null;
      ContentCachingRequestWrapper contentCachingRequestWrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
      if (null != contentCachingRequestWrapper) {
          byte[] buf = contentCachingRequestWrapper.getContentAsByteArray();
          if (buf.length > 0) {
              payloadData = new String(buf, 0, buf.length, contentCachingRequestWrapper.getCharacterEncoding());
          }
      }
      return payloadData;
  }  

  public 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;
    }



  @PostMapping(value = "/v1", consumes = { MediaType.APPLICATION_XML_VALUE,
      MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_XML_VALUE,
          MediaType.APPLICATION_JSON_VALUE })
  public PaymentResponse handleMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {


      HttpServletRequest requestCacheWrapperObject = new ContentCachingRequestWrapper(request);
      requestCacheWrapperObject.getParameterMap();

      .raw_request(readPayload(requestCacheWrapperObject))
      .raw_response(getResponseData(response))
  }

Но я получаю NULL за запрос и ответ. Знаете ли вы, как правильно получить полезную нагрузку из запроса и ответа?

1 Ответ

0 голосов
/ 22 мая 2019

Похоже, ваш вариант использования лучше всего подходит для класса, расширяющего org.springframework.web.servlet.handler.HandlerInterceptor класса Spring.

Пользовательские перехватчики могут переопределять preHandle и postHandle - оба они звучат так, как будто вы склонны использовать.

EDIT:

// add to wherevere your source code is
public class CustomInterceptor extends HandlerInterceptorAdapter {
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // TODO: use 'request' from param above and log whatever details you want
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
                // TODO: use 'response' from param above and log whatever details you want
    }
}


// add to your context
<mvc:interceptors>
    <bean id="customInterceptor" class="your.package.CustomInterceptor"/>
</mvc:interceptors>
...