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>
请提供示例程序。
使用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);
您将在输出中看到肥皂部分。
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
您可以为Saaj的本教程和对应的Javadocs。
假设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);