作者: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;
- }
- }
實例地址: