SOAP服务开发示例:使用Java实现服务端和客户端
SOAP服务开发示例:使用Java实现服务端和客户端
SOAP协议版本: 1.1、1.2
传输层协议: HTTP
安全标准: Web Service的安全策略
方法名: ckts_bgdInfo
命名空间: http://ws.dc.com
接口URL自定义,如: http://ip:port/services/recv?wsdl
消息模板:
<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ws='http://ws.dc.com'>
<soapenv:Header/>
<soapenv:Body>
<ws:ckts_bgdInfo>
<ws:xml>报文</ws:xml>
</ws:ckts_bgdInfo>
</soapenv:Body>
</soapenv:Envelope>
服务端代码
package com.dc.ws;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
@WebService
public class SampleService {
@WebMethod
public String ckts_bgdInfo(@WebParam(name = "xml") String xml) {
// 在这里处理接收到的报文
return "处理结果";
}
public static void main(String[] args) {
String url = "http://localhost:8080/services/recv";
SampleService service = new SampleService();
Endpoint.publish(url, service);
System.out.println("SOAP服务已启动,访问地址:" + url);
}
}
客户端代码
package com.dc.ws;
import javax.xml.namespace.QName;
import javax.xml.soap.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class SampleClient {
private static final String SERVICE_URL = "http://localhost:8080/services/recv?wsdl";
private static final String NAMESPACE_URI = "http://ws.dc.com";
private static final String METHOD_NAME = "ckts_bgdInfo";
public static void main(String[] args) {
try {
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("ws", NAMESPACE_URI);
SOAPBody soapBody = envelope.getBody();
SOAPElement soapElement = soapBody.addChildElement(METHOD_NAME, "ws");
SOAPElement xmlElement = soapElement.addChildElement("xml");
xmlElement.addTextNode("报文");
soapMessage.saveChanges();
SOAPMessage soapResponse = soapConnection.call(soapMessage, SERVICE_URL);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
soapResponse.writeTo(outputStream);
String response = new String(outputStream.toByteArray());
System.out.println("服务端返回:" + response);
soapConnection.close();
} catch (SOAPException | IOException e) {
e.printStackTrace();
}
}
}
注意: 替换服务端和客户端代码中的URL和命名空间为实际的值。然后,运行服务端代码启动SOAP服务,再运行客户端代码进行测试。
总结:
该示例提供了一个简单的SOAP服务实现,演示了如何使用SOAP API进行服务调用。通过修改代码中的URL、命名空间和方法名,可以轻松地实现不同的SOAP服务。
原文地址: https://www.cveoy.top/t/topic/NBb 著作权归作者所有。请勿转载和采集!