[英]how to add <soap:Envelope> and <soap:body> in xml request
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 格式,但是在向服務器發送請求之前,我需要在請求中添加上面的肥皂包和正文。
<?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。
您需要從要放入信封的對象中獲取一個 Document(在示例中使用 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 部分。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.