作者:http://blog.csdn.net/dreamfly88/article/details/52350370
因为工作需要,数据传输部分需要使用webservice实现,经过两天的研究,实现了一个简单的例子,具体方法如下。
首先需要新建一个项目,如图:
下一步点击finish,然后会生成一个webservice项目,在HelloWorld类里面写自己的方法,在file下编译一下这个类,不编译,idea会提示不通过,编译后需要将为该服务发布WSDL文件,此文件必须生成,如下图:
选择需要发布的服务
然后部署到TOMCAT,如图,这里需要注意的是需要引入这个库才能正常运行webservice
启动tomcat后,在浏览器中敲入如下代码:localhost:8080/services 回车测试webservice是否部署成功:
然后编写客户端测试代码,如下:
主要代码:
服务端:
- package example;
- import javax.jws.WebService;
- /**
- * Created by zhangqq on 2016/8/26.
- */
- public class HelloWorld {
- public String sayTitle(String from) {
- String result = "title is " + from;
- System.out.println(result);
- return result;
- }
- public String sayBody(String Other) {
- String result = "-------------body is-------------- " + Other;
- System.out.println(result);
- return result;
- }
- public String sayAll(String title,String body) {
- String result ="--------title:"+title+ "----------------/r/nbody:--------------------------- " + body;
- System.out.println(result);
- return result;
- }
- }
客户端:
- package test;
- import org.apache.axis.client.Call;
- import org.apache.axis.client.Service;
- import org.apache.axis.utils.StringUtils;
- import javax.xml.rpc.ServiceException;
- import java.net.MalformedURLException;
- /**
- * Created by zhangqq on 2016/8/29.
- */
- public class WebSvrClient {
- public static void main(String[] args) {
- String url = "http://localhost:8080/services/HelloWorldService";
- String method = "sayTitle";
- String[] parms = new String[]{"abc"};
- WebSvrClient webClient = new WebSvrClient();
- String svrResult = webClient.CallMethod(url, method, parms);
- System.out.println(svrResult);
- }
- public String CallMethod(String url, String method, Object[] args) {
- String result = null;
- if(StringUtils.isEmpty(url))
- {
- return "url地址为空";
- }
- if(StringUtils.isEmpty(method))
- {
- return "method地址为空";
- }
- Call rpcCall = null;
- try {
- //实例websevice调用实例
- Service webService = new Service();
- rpcCall = (Call) webService.createCall();
- rpcCall.setTargetEndpointAddress(new java.net.URL(url));
- rpcCall.setOperationName(method);
- //执行webservice方法
- result = (String) rpcCall.invoke(args);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return result;
- }
- }
实例地址:
源码下载地址