Spring:记录传出 HTTP 请求

Spring: Logging outgoing HTTP requests

我正在尝试在基于 spring 的 Web 应用程序中记录所有传出的 Http 请求。是否有用于此目的的拦截器?我想在离开应用程序之前记录所有传出的内容和 headers 。我正在使用 spring-ws 发送 SOAP 请求。所以基本上,我不仅要记录 SOAP 请求 xml(如此处所述 How can I make Spring WebServices log all SOAP requests?),还要记录整个 http 请求。

使用 WebServiceGatewaySupport 上的 ClientInterceptor 拦截 request/response:

// soapClient extends WebServiceGatewaySupport
soapClient.setInterceptors(new ClientInterceptor[]{new ClientInterceptor() {
        @Override
        public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            try {
                messageContext.getRequest().writeTo(os);
            } catch (IOException e) {
                throw new WebServiceIOException(e.getMessage(), e);
            }

            String request = new String(os.toByteArray());
            logger.trace("Request Envelope: " + request);
            return true;
        }

        @Override
        public boolean handleResponse(MessageContext messageContext) throws WebServiceClientException {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            try {
                messageContext.getResponse().writeTo(os);
            } catch (IOException e) {
                throw new WebServiceIOException(e.getMessage(), e);
            }

            String response = new String(os.toByteArray());
            logger.trace("Response Envelope: " + response);
            return true;
        }
        ...

要获得 headers,您还需要一个 TransportOutputStream 的实例。 不幸的是 class 是抽象的,所以你需要 subclass 是。它可能是这样的:

class ByteArrayTransportOutputStream extends TransportOutputStream {

    private ByteArrayOutputStream outputStream;

    @Override
    public void addHeader(String name, String value) throws IOException {
        createOutputStream();
        String header = name + ": " + value + "\n";
        outputStream.write(header.getBytes());
    }

    public byte[] toByteArray() {
         return outputStream.toByteArray();
    }

    @Override
    protected OutputStream createOutputStream() throws IOException {
        if (outputStream == null) {
            outputStream = new ByteArrayOutputStream();
        }
        return outputStream;
    }
}