Spring Interceptor - PullRequest
       60

Spring Interceptor

0 голосов
/ 11 марта 2020

Мне нужно создать перехватчик, который будет перехватывать HTTP-запросы и ответы, но мне кажется, что я делаю что-то не так, может кто-нибудь сказать мне, что я должен изменить или добавить?

public class HttpInterceptor extends HandlerInterceptorAdapter implements ClientHttpRequestInterceptor
{
    @Override
    public ClientHttpResponse intercept(final HttpRequest httpRequest, final byte[] bytes, final ClientHttpRequestExecution clientHttpRequestExecution) throws IOException
    {

        RestTemplate restTemplate = new RestTemplate();
        final ClientHttpResponse response = clientHttpRequestExecution.execute(httpRequest, bytes);
        final String httpResponseName = response.toString();

        final HttpHeaders httpHeaders = response.getHeaders();
        final HttpStatus httpStatusCode = response.getStatusCode();
        final String statusText = response.getStatusText();

        final String body = httpHeaders.toString() + httpStatusCode.toString() + statusText;
        //And then i will put body to DB

        return response;
    }

xml

<bean id="httpInterceptor" class="HttpInterceptor"/>
<bean id="httpInterceptor" class="de.hybris.platform.servicelayer.interceptor.impl.InterceptorMapping">
    <property name="interceptor" ref="httpInterceptor"/>
    <property name="typeCode" value="Message"/>
</bean>

Ответы [ 2 ]

0 голосов
/ 11 марта 2020

Я рекомендую реализовать фильтр для преобразования или использования информации, содержащейся в запросах или ответах. а не Interceptor, он предоставляет больше информации, чем Interceptor. Вот пример использования Filter для регистрации:

@Component
public class HttpLoggingFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(HttpLoggingFilter.class);

    @Value("${output.trace.actif}")
    private boolean isOutputActif;

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

    @Override
    public void init(FilterConfig filterConfig) {
        logger.info("start http filter");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        ContentCachingRequestWrapper requestToCache = new ContentCachingRequestWrapper(httpServletRequest);
        ContentCachingResponseWrapper responseToCache = new ContentCachingResponseWrapper(httpServletResponse);

        HttpUtil.majMDCRestInfo(httpServletRequest);

        long start = System.currentTimeMillis();

        chain.doFilter(requestToCache, responseToCache);

        long elapsedTime = System.currentTimeMillis() - start;

        String requestBody = new String(requestToCache.getContentAsByteArray());
        String responseBody = new String(responseToCache.getContentAsByteArray());

        final StringBuilder logMessage = new StringBuilder().append("[METHOD:").append(httpServletRequest.getMethod())
                .append("] [PARAMS:")
                .append(httpServletRequest.getQueryString()).append("] [BODY:").append(requestBody).append("]");

        if (isOutputActif) {
            String respContent = responseBody;
            if (respContent.equals("")) {
                respContent = "no data";
            }
            logMessage.append(" [RESPONSE:").append(respContent).append("]");
        }

        logMessage.append(" [STATUS:").append(responseToCache.getStatus()).append("] [Time:").append(elapsedTime).append("ms]");
        String[] nonLoggingPaths = {"/api/"};
        String urlPath = httpServletRequest.getRequestURL().toString();
        if ((Arrays.stream(nonLoggingPaths).parallel().anyMatch(urlPath::contains))) {
            logger.info("{}", logMessage);
        }

        getRequestData(requestToCache);
        getResponseData(responseToCache);
    }

}
0 голосов
/ 11 марта 2020

Я понял, что вы пытаетесь создать сервис (это может быть отдых, soap или любой другой). Если я прав, нужно создать контроллер для обработки http-запроса.

@Controller("MyController")
public class MyController extends AbstractController {
    @RequestMapping(value = "/mymethod/{id}", method = RequestMethod.GET)
    public void myMethod(@PathVariable final String id, final HttpServletRequest request, final HttpServletResponse out) throws Exception {
    try {
        if (StringUtils.isEmpty(id))
            throw new UnknownIdentifierException("id is null!");
        out.setContentType(MediaType.APPLICATION_TXT_VALUE);
        IOUtils.copy(myStream, out.getOutputStream());
    } catch (UnknownIdentifierException ex) {
        out.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.setContentType(MediaType.TEXT_PLAIN_VALUE);
        String message = "My error text!";
        IOUtils.copy(new ByteArrayInputStream(message.getBytes()), out.getOutputStream());
    } 
}
...