我正在尝试在基于 spring 的 Web 应用程序中记录所有传出的 Http 请求。是否有用于此目的的拦截器?我想在离开应用程序之前记录所有传出的内容和标题。我正在使用 spring-ws
发送 SOAP 请求。所以基本上,我不仅要记录 SOAP 请求 xml(如此处提到的 How can I make Spring WebServices log all SOAP requests? ),还要记录整个 http 请求。
最佳答案
使用 WebServiceGatewaySupport
上的 ClientInterceptor
拦截请求/响应:
// 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;
}
...
要同时获取 header ,您需要一个 TransportOutputStream
实例。
不幸的是这个类是抽象的,所以你需要子类化。它可能是这样的:
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;
}
}
关于java - Spring:记录传出的 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28380277/