服务端实现:
我们随便实现一个简单服务,客户请求我们的服务,我们给客户返回响应的信息
@WebService
public class HelloServiceImpl implements HelloService {
@Override
public String getString(String name) {
return "hello," + name;
}
}
这里用到了一个关键的注解@WebService表示该类是一个服务类,需要发布其中的public的方法
发布服务,Endpoint类发布服务,publish方法,两个参数:1.服务地址;2.服务实现类
package com.zlp.server;
import com.zlp.service.impl.HelloServiceImpl;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;
import javax.xml.ws.Endpoint;
@Component
public class HelloServer implements SmartLifecycle {
@Override
public void start() {
// spring容器启动之后执行当前方法内逻辑
System.out.println("webservice start");
Endpoint.publish("http://127.0.0.1:8808/hello", new HelloServiceImpl());
}
@Override
public void stop() {
System.out.println("webservice end");
}
@Override
public boolean isRunning() {
return false;
}
}
测试访问wsdl:
客户端实现:
1、直接通过命令行发送请求命令,webservice本质就http请求
2、Java代码实现:
package com.zlp.client;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class HelloClient {
public static void main(String[] args) throws Exception {
String requestSoapMessage = getRequestSoapMessage("webservice");
//System.out.println(requestSoapMessage);
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod("http://127.0.0.1:8808/hello?wsdl");
postMethod.setRequestBody(requestSoapMessage);
client.executeMethod(postMethod);
String xml = postMethod.getResponseBodyAsString();
System.out.println(xml);
// 解析xml数据
InputStream in = new ByteArrayInputStream(xml.getBytes("utf-8"));
SAXReader sax = new SAXReader();
Document document = sax.read(in);
Element root = document.getRootElement();
Element e = root.element("Body").element("getStringResponse").element("return");
System.out.println("result:" + e.getData().toString());
}
private static String getRequestSoapMessage(String name) {
String requestSoapMessage = "";
StringBuffer buf = new StringBuffer();
buf.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>")
.append("\n").append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:impl=\"http://impl.service.zlp.com/\"> ")
.append("\n").append("<soapenv:Header />")
.append("\n").append("<soapenv:Body>")
.append("\n").append("<impl:getString>")
.append("\n").append("<arg0>"+name+"</arg0>")
.append("\n").append("</impl:getString>")
.append("\n").append("</soapenv:Body>")
.append("\n").append("</soapenv:Envelope>");
requestSoapMessage = buf.toString();
return requestSoapMessage;
}
}
执行结果:
3、SoapUI客户端工具
输入wsdl地址: