我正在尝试创建一个简单的 SOAP 服务和一个 SOAP 客户端来运行一些性能测试。我是使用 SOAP 的新手,我只是想调整一些我在几个论坛上找到的代码。考虑到这个测试将在嵌入式设备上运行,我宁愿避免使用庞大的框架/库。我宁愿在 java 中编写代码而不使用 XML。
在下面的代码中,我试图调用“sayHello”方法并获得结果。它不完整(缺少参数),但我想修复它以便为我的测试提供一个起点。
你能帮我修复这个示例代码吗?
这是服务类的代码
@WebService(name = "Hello", targetNamespace = "http://localhost")
public class Hello
{
private String message = new String("Hello, ");
public void Hello()
{
}
public String sayHello(String name)
{
return message + name + ".";
}
}
这是服务器类的代码:
public class Server
{
protected Server() throws Exception
{
System.out.println("Starting Server");
Object implementor = new Hello();
String address = "http://localhost:9000/";
Endpoint.publish(address, implementor);
}
public static void main(String args[]) throws Exception
{
new Server();
System.out.println("Server ready...");
Thread.sleep(5 * 60 * 1000);
System.out.println("Server exiting");
System.exit(0);
}
}
这是客户端类的代码,旨在向调用 request() 方法的服务器发送请求:
public class Sender
{
.
.
.
public void request() throws Exception
{
// Building the request document
SOAPMessage reqMsg = MessageFactory.newInstance().createMessage();
SOAPEnvelope envelope = reqMsg.getSOAPPart().getEnvelope();
SOAPBody body = envelope.getBody();
body.addBodyElement(envelope.createName("Hello"));
// Connecting and calling
SOAPConnection con = SOAPConnectionFactory.newInstance()
.createConnection();
SOAPMessage resMsg = con.call(reqMsg, "http://localhost:9000/");
con.close();
// Showing output
System.out.println("\n\nRequest:");
reqMsg.writeTo(System.out);
System.out.println("\n\nResponse:");
resMsg.writeTo(System.out);
}
}
客户端的输出如下所示:
Request:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><SOAP-ENV:Body><Hello/></SOAP-ENV:Body></SOAP-ENV:Envelope>
Response:
<?xml version="1.0" ?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><S:Fault xmlns:ns3="http://www.w3.org/2003/05/soap-envelope"><faultcode>S:Client</faultcode><faultstring>Cannot find dispatch method for {}Hello</faultstring></S:Fault></S:Body></S:Envelope>
谢谢!