如何将字符串(XML)转换为soap消息

时间:2017-09-02 23:24:44

标签: java xml soap

当我在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());
}

1 个答案:

答案 0 :(得分:1)

看看这个:

XML Document to String?

我使用以下代码来解决我的问题:

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声明添加到输出中。如果您不想要它,应该可以轻松删除它。