how to add <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> in xml soap request.
我的示例请求如下所示。我创建了jaxb注释类并将对象编组为xml格式,但我需要在向服务器发送请求之前在请求中添加上面的soap envlope和body。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<StatusRequest>
<AccountID>231</AccountID>
<PassPhrase>sddddd</PassPhrase>
<StatusList>
<PICNumber>111111</PICNumber>
</StatusList>
<Test>Y</Test>
</StatusRequest>
请提供示例程序。
答案 0 :(得分:2)
使用javax.xml.soap。
您需要从要放入信封的对象中获取一个文档(在示例中使用JAXB封送它)并将其放入正文中。
这样:
MessageFactory mfactory = MessageFactory.newInstance();
SOAPMessage soapMessage = mfactory.createMessage();
SOAPBody soapBody = petition.getSOAPBody();
soapBody.addDocument(marshaller.marshallDoc(obj));
soapMessage.saveChanges();
这样做时:
soapMessage.writeTo(System.out);
您将在输出中看到SOAP部分。
答案 1 :(得分:1)
SOAPPart soapPart = message.getSOAPPart();
// Obtain SOAP Part
SOAPEnvelope envelope = soapPart.getEnvelope();
// Obtain Envelope from SOAP Part
SOAPHeader header = envelope.getHeader();
// Obtain Header from Envelope
SOAPBody body = envelope.getBody();
// Obtain Body from Envelope
QName headerName = new QName("namespaceURI", "localPart");
// SOAPHeaderElement must have an associated QName object.
SOAPHeaderElement headerElement = header.addHeaderElement(headerName);
// Create new SOAPHeaderElement object initialized with the specified Qname
// and add it to this SOAPHeader object.
headerElement.addAttribute(new QName("localPart"), "valueToAdd");
// Add attribute to header
QName bodyName = new QName("namespaceURI", "localPart");
// SOAPBodyElement must have an associated QName object.
SOAPBodyElement bodyElement = body.addBodyElement(bodyName);
// Add Body Element
您可以使用此tutorial和SAAJ的相应JavaDoc。
答案 2 :(得分:0)
假设req
是一个用javax.xml.bind.annotation
标记的类,则:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
marshaller.marshal(req, doc);
MessageFactory mfactory = MessageFactory.newInstance();
SOAPMessage soapMessage = mfactory.createMessage();
SOAPBody soapBody = soapMessage.getSOAPBody();
soapBody.addDocument(doc);
var baos = new ByteArrayOutputStream();
soapMessage.writeTo(baos);
var str = new String(baos.toByteArray(), Charset.forName("UTF8"));
log.info("SOAPMessage: {}", str);