当我为 SOAPBOAY 使用下面的代码时,我得到了 null,这是怎么回事。过去 3 天我在挣扎。在我的项目中,我想将响应转换为类对象,但是当我打印 message.getSOAPBody().toString() 时,它以 NULL 形式出现。请回答任何问题,这将有助于我的服务自动化项目。
String resMessage = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + "<soapenv:Envelope\r\n"
+ " xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\r\n"
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\r\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + " <soapenv:Header>\r\n"
+ " <ns1:RequestHeader\r\n"
+ " soapenv:actor=\"http://schemas.xmlsoap.org/soap/actor/next\"\r\n"
+ " soapenv:mustUnderstand=\"0\"\r\n"
+ " xmlns:ns1=\"https://www.google.com/apis/ads/publisher/v201705\">\r\n"
+ " <ns1:networkCode>123456</ns1:networkCode>\r\n"
+ " <ns1:applicationName>DfpApi-Java-2.1.0-dfp_test</ns1:applicationName>\r\n"
+ " </ns1:RequestHeader>\r\n" + " </soapenv:Header>\r\n" + " <soapenv:Body>\r\n"
+ " <getAdUnitsByStatement xmlns=\"https://www.google.com/apis/ads/publisher/v201705\">\r\n"
+ " <filterStatement>\r\n" + " <query>WHERE parentId IS NULL LIMIT 500</query>\r\n"
+ " </filterStatement>\r\n" + " </getAdUnitsByStatement>\r\n" + " </soapenv:Body>\r\n"
+ "</soapenv:Envelope>";
// Create SoapMessage
MessageFactory msgFactory = MessageFactory.newInstance();
SOAPMessage message = msgFactory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
// Load the SOAP text into a stream source
byte[] buffer = resMessage.getBytes();
ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
StreamSource source = new StreamSource(stream);
// Set contents of message
soapPart.setContent(source);
// -- DONE
message.writeTo(System.out);
if (message != null) {
System.out.println("The Response Body is " + message.getSOAPBody().toString());
}
最佳答案
看看这个:
我使用这段代码解决了我的问题:
public static String toString(Document doc) {
try {
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(doc), new StreamResult(sw));
return sw.toString();
} catch (Exception ex) {
throw new RuntimeException("Error converting to String", ex);
}
}
似乎有点啰嗦,但效果很好,而且我不需要设置输出属性(将它们留在那里以防万一)。它甚至在输出中添加了一个 xml 声明。如果您不想要它,应该可以轻松将其删除。
关于java - 如何将字符串(XML)转换为 SOAP 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46019047/