WebService接口的生成和调用(WebService接口)

花生 可爱的博主

时间: 2023-11-24 阅读: 1 字数:20755

{}
二:Webservice客户端调用: 1:本地生成代码,直接调用: 2、利用dos命令生成代码,和第一种基本一致 3:利用apache的AXIS直接调用远程的web service 4:service编程实现调用 5:Ht......

Web Service是构建互联网分布式系统的基本部件,它是一个应用程序,它向外界暴露出一个能够通过Web进行调用的API。这就是说,别人能够用编程的方法通过Web来调用这个应用程序。

它通过标准通信协议,在互联网上以服务的方式发布有用的程序模块,目前大部分是用SOAP作为通信协议。

它提供一份详细的接口说明书,来帮助用户构建应用程序,这个接口说明书叫WSDL(Web服务描述语言,Web Service Description Language)。

请求报文和返回报文都是XML格式的,XML(Extensible Markup Language)即可扩展标记语言,它与HTML一样,都是SGML(Standard Generalized MarkupLanguage,标准通用标记语言)。

一:WebService的服务端发布

1:发布web程序服务端发布

           创建 service 接口

           创建接口实现类,实现业务逻辑

                 配置 web.xml 中 中 Xfire
                   提供对 xfire 的拦截

     配置 webservice  配置
          在 class 目录下建立 META-INF 目录,如(META-INF>xfire->services.xml),在
          services.xml 文件中进行 webservice 服务的发布.

然后启动服务,在浏览器中输入http://ip/项目名称/services就可以看到发布的接口了

2:本地发布

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;

/**
* Title: ServiceHello
* Description: 基于jdk1.6以上的javax.jws 发布webservice接口
            @WebService - 它是一个注解,用在类上指定将此类发布成一个ws。
            Endpoint – 此类为端点服务类,它的方法publish用于将一个已经添加了@WebService注解
            对象绑定到一个地址的端口上。 
* Version:1.0.0  
* @author panchengming
 */
@WebService  
public class JwsServiceHello {

   /** 供客户端调用方法  该方法是非静态的,会被发布
    * @param name  传入参数
    * @return String 返回结果
    * */
   public String getValue(String name){
      return "欢迎你! "+name;
   }

   /**
    * 方法上加@WebMentod(exclude=true)后,此方法不被发布;
    * @param name
    * @return
    */
   @WebMethod(exclude=true)  
   public String getHello(String name){
      return "你好! "+name;
   }

   /** 静态方法不会被发布
    * @param name
    * @return
    */
   public static String getString(String name){
      return "再见!"+name;
   }


    //通过EndPoint(端点服务)发布一个WebService
   public static void main(String[] args) {
    /*参数:1,本地的服务地址;
         2,提供服务的类;
     */
    Endpoint.publish("http://192.168.1.105:8080/Service/ServiceHello", new JwsServiceHello());
    System.out.println("发布成功!");
    //发布成功后 在浏览器输入 http://192.168.1.105:8080/Service/ServiceHello?wsdl
   }
}

二:Webservice客户端调用:

1:本地生成代码,直接调用:

1:新建一个class类,用于调用webservice。右键src,找到Web Service Client,并输入wsdl地址,选择下载代码的路径;

(url: <a href="http://192.168.1.105:8080/Service/ServiceHello?wsdl" title="http://192.168.1.105:8080/Service/ServiceHello?wsdl">http://192.168.1.105:8080/Service/ServiceHello?wsdl</a>)

2.将地址上的文件下载下来(注意和发布JDK一致); 3.写调用方法调用下载下来的WebService中的java类中的方法; 示例:

import com.pcm.ws.jws.JwsServiceHello;
import com.pcm.ws.jws.JwsServiceHelloService;

/**
 * 
* Title: JwsClientHello
* Description: webService 客户端调用
* Version:1.0.0  
* @author panchengming
 */
public class JwsClientHello {

   public static void main(String[] args) {
       //调用webservice
      JwsServiceHello hello=new JwsServiceHelloService().getJwsServiceHelloPort();
      String name=hello.getValue("panchengming");
      System.out.println(name);
   }
}

2、利用dos命令生成代码,和第一种基本一致

A、在工作空间创建用于存放使用wsimport命令生成的客户端代码的java工程

B、使用jdk提供的wsimport命令生成客户端代码

● wsimport命令是jdk提供的,作用是根据使用说明书生成客户端代码,wsimport只支持SOAP1.1客户端的生成

● wsimport常用参数

-d:默认参数,用于生成.class文件 -s:生成.java文件 -p:指定生成java文件的包名,不指定则为WSDL说明书中namespace值得倒写

C、在doc窗口进入java工程项目的src目录,执行wsimport命令

D、在Eclipse中刷新java项目,将生成的客户端代码copy到客户端工程中

E、创建服务视图,类名从<service>标签的name属性获取

F、获取服务实现类,视图实例调用getProt()方法,实现类的类名从portType的name属性获取

G、调用查询方法,方法名从portType下的operation标签的name属性获取

package com.webservice.client;


import com.webservice.jaxws.WeatherServiceImpl;

import com.webservice.jaxws.WeatherServiceImplService;


public class Client {


public static void main(String[] args) {

//创建视图

WeatherServiceImplService wsis = new WeatherServiceImplService();

//获取服务实现类

WeatherServiceImpl wsi = wsis.getPort(WeatherServiceImpl.class);

//调用查询方法

String weather = wsi.queryWeather("北京");

System.out.println(weather);

}

}

● <service> 服务视图,webservice的服务结点,它包括了服务端点

● <binding> 为每个服务端点定义消息格式和协议细节


服务端点,描述 web service可被执行的操作方法,以及相关的消息,通过binding指向portType

● <message> 定义一个操作(方法)的数据参数(可有多个参数)

● <types> 定义 web service 使用的全部数据类型

3:service编程实现调用

注意: (1)该种方式可以自定义关键元素,方便以后维护,是一种标准的开发方式; (2)这种方式同样需要wsimport生成客户端代码,只不过仅需要将服务接口类引入即可,例如如果需要<wsdl:port name="MobileCodeWSSoap" binding="tns:MobileCodeWSSoap">端口服务,则需要将生成的MobileCodeWSSoap.class类引入;

(1)、开发步骤

A、wisimport生成客户端代码

B、使用serivce类创建服务视图

C、获取服务实现类

D、调用查询方法

import java.io.IOException;  
import java.net.MalformedURLException;  
import java.net.URL;  
  
import javax.xml.namespace.QName;  
import javax.xml.ws.Service;  
  
import cn.itcast.mobile.MobileCodeWSSoap;  
  
/** 
 *  
 *  Title: ServiceClient.java
 *  Description:Service编程实现服务端调用
 *  这种方式同样需要wsimport生成客户端代码,只不过仅需要将服务接口类引入即可,例如如果需要
 *  <wsdl:port name="MobileCodeWSSoap" binding="tns:MobileCodeWSSoap">
 *  端口服务,则需要将生成的MobileCodeWSSoap.class类引入
 */  
public class ServiceClient {  
  
   public static void main(String[] args) throws IOException {  
      //创建WSDL地址,不是服务地址  
      URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl");  
      //创建服务名称  
      //1.namespaceURI - 命名空间地址 (wsdl文档中的targetNamespace)
      //2.localPart - 服务视图名  (wsdl文档中服务名称,例如<wsdl:service name="MobileCodeWS">)
      QName qname = new QName("http://WebXml.com.cn/", "MobileCodeWS");  
        
      //Service创建视图  
      //参数:  
      //1.wsdlDocumentLocation - 使用说明书地址  
      //2.serviceName - 服务名称  
      Service service = Service.create(url, qname);  
      //获取服务实现类 
      //参数解释:serviceEndpointInterface - 服务端口(wsdl文档中服务端口的name属性,例如<wsdl:port name="MobileCodeWSSoap" binding="tns:MobileCodeWSSoap">)
      MobileCodeWSSoap mobileCodeWSSoap = service.getPort(MobileCodeWSSoap.class);  
      //调用查询方法  
      String result = mobileCodeWSSoap.getMobileCodeInfo("188888888", "");  
      System.out.println(result);  
   }  
}

4:利用apache的AXIS直接调用远程的web service

public static void axis() {
      Service service = new Service();
      try {
         Call call = (Call) service.createCall();
         //设置地址
         call.setTargetEndpointAddress("http://www.webxml.com.cn/WebServices/ValidateEmailWebService.asmx?wsdl");
         call.setUseSOAPAction(true);

         //域名加方法,//上面有写着targetNamespace="http://x.x.x/",这个就是你的命名空间值了;加方法名
         call.setSOAPActionURI("http://WebXml.com.cn/" + "ValidateEmailAddress");


         // 设置要调用哪个方法
         call.setOperationName(new QName("http://WebXml.com.cn/", "ValidateEmailAddress")); // 设置要调用哪个方法
         //设置参数名 :参数名 ,参数类型:String, 参数模式:'IN' or 'OUT'
         call.addParameter(new QName("http://WebXml.com.cn/", "theEmail"), // 设置要传递的参数
               org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);

         call.setEncodingStyle("UTF-8");
         //返回类型
         call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// (标准的类型)

         // 调用方法并传递参数
         String res = String.valueOf(call.invoke(new Object[]{"wangkanglu1024@163.com"}));
         System.out.println(res);

      } catch (Exception ex) {
         ex.printStackTrace();
      }
 public static void axis2() throws MalformedURLException, SOAPException, ServiceException, RemoteException {
      String endpoint = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl";
      String res = null;
      // 查询电话号码的接口方法名
      String operationName = "getMobileCodeInfo";
      // 定义service对象
      Service service = new Service();
      // 创建一个call对象
      Call call = (Call) service.createCall();
      // 设置目标地址,即webservice路径
      call.setTargetEndpointAddress(endpoint);
      // 设置操作名称,即方法名称   targetNamespace="http://WebXml.com.cn/"
      call.setOperationName(new QName("http://WebXml.com.cn/", operationName));
      // 设置方法参数
      call.addParameter(new QName("http://WebXml.com.cn/", "mobileCode"),
            org.apache.axis.encoding.XMLType.XSD_STRING,
            javax.xml.rpc.ParameterMode.IN);
      call.addParameter(new QName("http://WebXml.com.cn/", "userID"),
            org.apache.axis.encoding.XMLType.XSD_STRING,
            javax.xml.rpc.ParameterMode.IN);
      // 设置返回值类型
      //对于返回是字符串数组的返回类型只有这两种可行

      //call.setReturnType(org.apache.axis.encoding.XMLType.SOAP_VECTOR);
      call.setReturnClass(java.lang.String.class);

      call.setUseSOAPAction(true);
      call.setSOAPActionURI("http://WebXml.com.cn/" + "getMobileCodeInfo");

      res = (String) call.invoke(new Object[]{"15611111111", "0"});

      // 如果返回类型是org.apache.axis.encoding.XMLType.SOAP_VECTOR时用下面的转型接收
      //Vector v=(Vector) call.invoke(new Object[]{cityCode,userId});

      System.out.println(res);

   }

5:HttpURLConnection调用方式

(1)、开发步骤

A、创建服务地址

B、打开服务地址的一个连接

C、设置连接参数

● 注意

a、POST必须大写,如果小写会出如下异常: b、如果不设置输入输出,会报异常

D、组织SOAP协议数据,发送给<a href="https://www.baidu.com/s?wd=%E6%9C%8D%E5%8A%A1%E5%99%A8&tn=24004469_oem_dg&rsv_dl=gh_pl_sl_csd" title="服务器">服务器</a>

E、接收服务端的响应

import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.io.OutputStream;  
import java.net.HttpURLConnection;  
import java.net.MalformedURLException;  
import java.net.URL;  
  
/**
 * 
* @ClassName: HttpURLConectionMode 
* @Description: TODO(通过HttpURLConnection发送http请求) 
*   sope协议,比较麻烦的是需要拼接xml格式的请求数据
* @author
* @date 2017年11月8日 上午9:18:24 
*
 */
public class HttpClient {  
  
   public static void main(String[] args) throws IOException {  
      //第一步:创建服务地址,不是WSDL地址 
      URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");  
      //2:打开到服务地址的一个连接  
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
      //3:设置连接参数  
      //3.1设置发送方式:POST必须大写  
      connection.setRequestMethod("POST");  
      //3.2设置数据格式:Content-type  
      connection.setRequestProperty("content-type", "text/xml;charset=utf-8");  
      //3.3设置输入输出,新创建的connection默认是没有读写权限的,  
      connection.setDoInput(true);  
      connection.setDoOutput(true);  
  
      //4:组织SOAP协议数据,发送给服务端  
      String soapXML = getXML("1866666666");  
      OutputStream os = connection.getOutputStream();  
      os.write(soapXML.getBytes());  
        
      //5:接收服务端的响应  
      int responseCode = connection.getResponseCode();  
      if(200 == responseCode){//表示服务端响应成功  
         InputStream is = connection.getInputStream();  
         InputStreamReader isr = new InputStreamReader(is);  
         BufferedReader br = new BufferedReader(isr);  
           
         StringBuilder sb = new StringBuilder();  
         String temp = null;  
           
         while(null != (temp = br.readLine())){  
            sb.append(temp);  
         }  
           
         System.out.println(sb.toString());  
           
         is.close();  
         isr.close();  
         br.close();  
      }  
  
      os.close();  
   }  
     
   /** 
    * <?xml version="1.0" encoding="utf-8"?> 
      <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> 
         <soap:Body> 
            <getMobileCodeInfo xmlns="http://WebXml.com.cn/"> 
               <mobileCode>string</mobileCode> 
               <userID>string</userID> 
            </getMobileCodeInfo> 
         </soap:Body> 
      </soap:Envelope> 
    * @param phoneNum 
    * @return 
    */  
   public static String getXML(String phoneNum){  
      String soapXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"  
      +"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"  
         +"<soap:Body>"  
         +"<getMobileCodeInfo xmlns=\"http://WebXml.com.cn/\">"  
            +"<mobileCode>"+phoneNum+"</mobileCode>"  
           +"<userID></userID>"  
         +"</getMobileCodeInfo>"  
       +" </soap:Body>"  
      +"</soap:Envelope>";  
      return soapXML;  
   }  
}  

提供一个比较完善一点的工具类

public Map<String, Object> webServiceRequestUtil(String requesturl, String soapXML) throws IOException, ZycxException {
      
      HttpURLConnection connection = null;
      OutputStream os = null;
      Map<String, Object> reslut = new HashMap<>();

      try {
         //1:创建服务地址
         URL url = new URL(requesturl);
         //2:打开到服务地址的一个连接
         connection = (HttpURLConnection) url.openConnection();
         //3:设置连接参数
         //3.1设置发送方式:POST必须大写
         connection.setRequestMethod("POST");
         //3.2设置数据格式:Content-type
         connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
         //3.3设置输入输出,新创建的connection默认是没有读写权限的,
         connection.setDoInput(true);
         connection.setDoOutput(true);

         //4:组织SOAP协议数据,发送给服务端
         os = connection.getOutputStream();
         os.write(soapXML.getBytes());
      } catch (IOException e) {
         throw new myException("链接webservice出错!url为:" + requesturl + ";exception:" + e);
      }
      
      StringBuilder sb = new StringBuilder();
      InputStream is = null;
      InputStreamReader isr = null;
      BufferedReader br = null;
      try {
         String temp = null;
         //5:接收服务端的响应
         int responseCode = connection.getResponseCode();
         
         if (200 == responseCode) {//表示服务端响应成功
            is = connection.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);

            while ((temp = br.readLine()) != null) {
               sb.append(temp);
            }

            //这是我自己封装了一个map的返回格式,封装了headr和body
            reslut = ReturnUtil.returnjSON(BackStatus.BACK_STATUS_OK, "success", sb.toString());
         } else {
            is = connection.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);

            while ((temp = br.readLine()) != null) {
               sb.append(temp);
            }
            reslut = ReturnUtil.returnjSON(BackStatus.BACK_STATUS_EXCEPTION + "", "请求出错,http响应为:"+responseCode, sb.toString());
         
         }
      } catch (IOException e) {
         throw new myException("返回结果解析出错" + e);
      } finally {
         if(!Objects.isNull(br)){
            br.close();
         }
         if(!Objects.isNull(isr)){
            isr.close();
         }
         if(!Objects.isNull(is)){
            is.close();
         }
         if(!Objects.isNull(os)){
            os.close();
         }
      }

      
      return reslut;
   }

6.Ajax调用方式


<!doctype html>  
<html lang="en">  
 <head>  
  <title>Ajax调用方式</title>  
  <script type="text/javascript">  
   function queryMobile(){  
      //创建XMLHttpRequest对象  
      var xhr = new XMLHttpRequest();  
      //打开链接  
      xhr.open("post","http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx",true);  
      //设置content-type  
      xhr.setRequestHeader("content-type","text/xml;charset=utf-8");  
  
      //设置回调函数  
      xhr.onreadystatechange=function(){  
         //判断客户端发送成功&amp;&amp;服务端响应成功  
         if(4 == xhr.readyState &amp;&amp; 200 == xhr.status){  
            alert(xhr.responseText);  
         }  
      }  
  
      //组织SOAP协议数据  
      var soapXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"  
      +"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"  
         +"<soap:Body>"  
         +"<getMobileCodeInfo xmlns=\"http://WebXml.com.cn/\">"  
            +"<mobileCode>"+document.getElementById("phoneNum").value+"</mobileCode>"  
           +"<userID></userID>"  
         +"</getMobileCodeInfo>"  
       +" </soap:Body>"  
      +"</soap:Envelope>";  
      alert(soapXML);  
  
      //发送请求  
      xhr.send(soapXML);  
   }  
  </script>  
 </head>  
 <body>  
   手机号归属地查询:<input type="text" id="phoneNum" /><input type="button" value="查询" onclick="javascript:queryMobile();"/>  
 </body>  
</html>

参考文章:<a href="https://blog.csdn.net/qq_35124535/article/details/62226585#t2" title="java调用webservice接口 几种方法_yesIcando-bupt的博客-CSDN博客_java 调webservice接口">java调用webservice接口 几种方法_yesIcando-bupt的博客-CSDN博客_java 调webservice接口</a>

整理至此,希望对大家有帮助

原文地址:https://blog.csdn.net/qq_41694906/article/details/88029533?ops_request_misc%3D%25257B%252522request%25255Fid%252522%25253A%252522170080622516800186512075%252522%25252C%252522scm%252522%25253A%25252220140713.130102334..%252522%25257D%26request_id%3D170080622516800186512075%26biz_id%3D0%26utm_medium%3Ddistribute.pc_search_result.none-task-blog-2%7Eall%7Ebaidu_landing_v2%7Edefault-5-88029533-null-null.142%5Ev96%5Epc_search_result_base9%26utm_term%3D%25E8%25B0%2583%25E7%2594%25A8webservice

本文章网址:https://www.sjxi.cn/detil/9e7f101345004d03b68335daf40bce87

最新评论

当前未登陆哦
登陆后才可评论哦

湘ICP备2021009447号

×

(穷逼博主)在线接单

QQ: 1164453243

邮箱: abcdsjx@126.com

前端项目代做
前后端分离
Python 爬虫脚本
Java 后台开发
各种脚本编写
服务器搭建
个人博客搭建
Web 应用开发
Chrome 插件编写
Bug 修复