我正在使用WebServices和Apache Camel,并使用dataFormat作为POJO来请求该Web服务。我成功地能够调用该服务,但我想记录请求和响应SOAP消息,这是我无法做到的,因为SOAP消息是由CXF从POJO类创建的。
当dataFormat是POJO时,我有什么办法可以记录请求和响应SOAP消息吗?
答案 0 :(得分:0)
这是我在项目中记录soap请求和响应的示例,希望这有帮助
BindingProvider bindingProvider = ((BindingProvider) PortType);
List<Handler> handlerChain = bindingProvider.getBinding().getHandlerChain();
handlerChain.add(new SOAPLoggingHandler());
bindingProvider.getBinding().setHandlerChain(handlerChain);
和类 SOAPLoggingHandler
public class SOAPLoggingHandler implements SOAPHandler<SOAPMessageContext> {
// change this to redirect output if desired
public static Logger logger = Logger.getLogger("GetCustomerDataLand");
public Set<QName> getHeaders() {
return null;
}
public boolean handleMessage(SOAPMessageContext smc) {
logToSystemOut(smc);
return true;
}
public boolean handleFault(SOAPMessageContext smc) {
logToSystemOut(smc);
return true;
}
// nothing to clean up
public void close(MessageContext messageContext) {
}
/*
* Check the MESSAGE_OUTBOUND_PROPERTY in the context to see if this is an
* outgoing or incoming message. Write a brief message to the print stream
* and output the message. The writeTo() method can throw SOAPException or
* IOException
*/
private void logToSystemOut(SOAPMessageContext smc) {
Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:sss").format(new Date()) + "\nOutbound message:");
} else {
logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:sss").format(new Date()) + "\nInbound message:");
}
SOAPMessage message = smc.getMessage();
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
message.writeTo(stream);
String msg = new String(stream.toByteArray(), "utf-8");
logger.info(toPrettyString(msg));
// message.writeTo(out);
logger.info(""); // just to add a newline
} catch (Exception e) {
logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:sss").format(new Date()) + "Exception in handler: "
+ org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(e));
}
}
public String toPrettyString(String xml) {
try {
final InputSource src = new InputSource(new StringReader(xml));
final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src)
.getDocumentElement();
final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
final LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
writer.getDomConfig().setParameter("xml-declaration", keepDeclaration);
return writer.writeToString(document);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}