我正在尝试在基于Spring的Web应用程序中记录所有传出的Http请求。为此目的是否有拦截器?我想在离开应用程序之前记录所有传出的内容和标题。我正在使用spring-ws
发送SOAP请求。所以基本上,我不仅要记录SOAP请求xml(这里提到How can I make Spring WebServices log all SOAP requests?),还要记录整个http请求。
答案 0 :(得分:4)
使用ClientInterceptor
上的WebServiceGatewaySupport
拦截请求/回复:
// 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;
}
...
要获取标题,您需要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;
}
}