【发布时间】:2019-11-12 18:42:18
【问题描述】:
我正在开发一个基于肥皂的网络服务应用程序。该设计有我们自己的自定义代码来生成 WSDL 和 SOAP 回复。需要支持 SOAP 1.1 和 SOAP 1.2。用于支持这种设计的最佳 SOAP 库是什么。
【问题讨论】:
标签: soap
我正在开发一个基于肥皂的网络服务应用程序。该设计有我们自己的自定义代码来生成 WSDL 和 SOAP 回复。需要支持 SOAP 1.1 和 SOAP 1.2。用于支持这种设计的最佳 SOAP 库是什么。
【问题讨论】:
标签: soap
找到答案了。
JDK 1.7或更高版本确实有“javax.xml.soap”包。我们可以很容易地在两种格式之间切换。一个只需要传入SOAP协议/版本的SOAP.javax.xml.soap。 SOAPConstant 包含所有必需的常量字段。这是示例代码。
package test;
import javax.xml.soap.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class SOAPGenerator {
/**
* The test namespace.
*/
public static final String NS = "http://www.test.com/xml/soap/";
/**
* Default encoding of the underlying XML in a SOAPMessage
*/
public static final String DEFAULT_ENCODING = "UTF-8";
public static void main(String[] args) {
SOAPMessage soapMessage11 = null;
SOAPMessage soapMessage12 = null;
soapMessage11 = generateSOAP("1.1");
soapMessage12 = generateSOAP("1.2");
try {
soapMessage11.writeTo(new FileOutputStream(new File("gen_soap11.xml")));
soapMessage12.writeTo(new FileOutputStream(new File("gen_soap12.xml")));
} catch (SOAPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static SOAPMessage generateSOAP(String version) {
SOAPMessage soapMsg = null;
String connectionId = "testing";
int transactionId = 1;
try {
String protocol;
if("1.1".equalsIgnoreCase(version)){
protocol = SOAPConstants.SOAP_1_2_PROTOCOL;
} else {
protocol = SOAPConstants.SOAP_1_1_PROTOCOL;
}
MessageFactory messageFactory = MessageFactory.newInstance(protocol);
soapMsg = messageFactory.createMessage();
//setting the namespace declaration.
SOAPPart sp = soapMsg.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
se.addNamespaceDeclaration("test", NS);
soapMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, DEFAULT_ENCODING);
soapMsg.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
//setting the soap header.
SOAPHeader soapHeader = soapMsg.getSOAPHeader();
//setting the session id
SOAPElement soapHeaderElement1 = soapHeader.addChildElement("session", "lw", NS);
soapHeaderElement1.addTextNode(connectionId);
//setting the transactionId
SOAPElement soapHeaderElement2 = soapHeader.addChildElement("transactionId", "lw", NS);
soapHeaderElement2.addTextNode(String.valueOf(transactionId));
} catch (SOAPException e) {
e.printStackTrace();
}
return soapMsg;
}
`}
【讨论】: