【问题标题】:Generate SOAP Message from java String从 java 字符串生成 SOAP 消息
【发布时间】:2015-09-18 07:38:45
【问题描述】:

我写了从java字符串生成soap消息的方法:

private SOAPMessage createRequest(String msg) {
    SOAPMessage request = null;
    try {
        MessageFactory msgFactory = MessageFactory.newInstance();
        request = factory.createMessage();

        SOAPPart msgPart = request.getSOAPPart();
        SOAPEnvelope envelope = msgPart.getEnvelope();
        SOAPBody body = envelope.getBody();

        StreamSource _msg = new StreamSource(new StringReader(msg));
        msgPart.setContent(_msg);

        request.saveChanges();
    } catch(Exception ex) {
       ex.printStackTrace();
    }
}

然后,我尝试生成一些消息。例如:

createRequest("test message");

但是在这里 - request.saveChanges(); 我发现了这个异常: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Error during saving a multipart message

我的错误在哪里?

【问题讨论】:

  • 你没有阅读整个异常堆栈,最重要的部分应该是 org.xml.sax.SAXParseException;行号:1;列号:1; prolog 中不允许内容,这意味着您的 msg 首先应该是有效的 XML。

标签: java string soap saaj


【解决方案1】:

那是因为您没有传递正确的 protocol 格式的消息。 您的代码没有指定您要使用的 SOAP 协议,这意味着它为 SOAP 1.1 消息创建了一个消息工厂。

因此,您需要传递正确的 SOAP1.1 消息。 我复制了你的方法是这样的:

private static SOAPMessage createRequest(String msg) {
        SOAPMessage request = null;
        try {
            MessageFactory msgFactory = MessageFactory
                    .newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
            request = msgFactory.createMessage();

            SOAPPart msgPart = request.getSOAPPart();
            SOAPEnvelope envelope = msgPart.getEnvelope();
            SOAPBody body = envelope.getBody();

            javax.xml.transform.stream.StreamSource _msg = new javax.xml.transform.stream.StreamSource(
                    new java.io.StringReader(msg));
            msgPart.setContent(_msg);

            request.saveChanges();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return request;
    }

我用这个字符串来称呼它:

String soapMessageString = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body></SOAP-ENV:Body></SOAP-ENV:Envelope>";
createRequest(soapMessageString);

它有效。

【讨论】:

    猜你喜欢
    • 2016-09-17
    • 2012-04-20
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 2012-01-16
    相关资源
    最近更新 更多