我在JAX-WS中设置了一个SOAP WebServiceProvider,但是我无法弄清楚如何从SOAPMessage(或任何Node)对象中获取原始XML.这是我现在获得的代码示例,以及我在尝试获取XML的地方:
@WebServiceProvider(wsdlLocation="SoapService.wsdl") @ServiceMode(value=Service.Mode.MESSAGE) public class SoapProvider implements Provider{ public SOAPMessage invoke(SOAPMessage msg) { // How do I get the raw XML here? } }
有没有一种简单的方法来获取原始请求的XML?如果有办法通过设置不同类型的Provider(例如Source)来获取原始XML,我也愿意这样做.
你可以试试这种方式.
SOAPMessage msg = messageContext.getMessage(); ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); String strMsg = new String(out.toByteArray());
如果您有SOAPMessage
或SOAPMessageContext
,您可以使用a Transformer
,将其转换为Source
via DOMSource
:
final SOAPMessage message = messageContext.getMessage(); final StringWriter sw = new StringWriter(); try { TransformerFactory.newInstance().newTransformer().transform( new DOMSource(message.getSOAPPart()), new StreamResult(sw)); } catch (TransformerException e) { throw new RuntimeException(e); } // Now you have the XML as a String: System.out.println(sw.toString());
这将考虑编码,因此您的"特殊字符"不会被破坏.
事实证明,可以通过使用Provider
import java.io.ByteArrayOutputStream; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.ws.Provider; import javax.xml.ws.Service; import javax.xml.ws.ServiceMode; import javax.xml.ws.WebServiceProvider; @ServiceMode(value=Service.Mode.PAYLOAD) @WebServiceProvider() public class SoapProvider implements Provider
我最终不需要这个解决方案,所以我自己没有尝试过这个代码 - 它可能需要一些调整才能正确.但我知道这是从Web服务获取原始XML的正确途径.
(如果你绝对必须拥有一个SOAPMessage对象,我不确定如何使这个工作,但是如果你将要处理原始XML,那么为什么你会使用更高级别的对象呢?)
仅用于调试目的,使用一行代码 -
msg.writeTo(System.out);
如果需要将xml字符串格式化为xml,请尝试以下操作:
String xmlStr = "your-xml-string"; Source xmlInput = new StreamSource(new StringReader(xmlStr)); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(xmlInput, new StreamResult(new FileOutputStream("response.xml")));
使用Transformer Factory:
public static String printSoapMessage(final SOAPMessage soapMessage) throws TransformerFactoryConfigurationError, TransformerConfigurationException, SOAPException, TransformerException { final TransformerFactory transformerFactory = TransformerFactory.newInstance(); final Transformer transformer = transformerFactory.newTransformer(); // Format it transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); final Source soapContent = soapMessage.getSOAPPart().getContent(); final ByteArrayOutputStream streamOut = new ByteArrayOutputStream(); final StreamResult result = new StreamResult(streamOut); transformer.transform(soapContent, result); return streamOut.toString(); }