从java String

时间:2015-09-18 07:38:46

标签: java string soap saaj

我写了一个方法,它从java string生成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

我的错误在哪里?

1 个答案:

答案 0 :(得分:0)

这是因为您没有传递正确的协议格式的消息。 您的代码未指定要使用的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);

并且有效。