ToB企服应用市场:ToB评测及商务社交产业平台

标题: Java开辟或调用WebService的几种方式 [打印本页]

作者: 悠扬随风    时间: 2024-7-25 12:56
标题: Java开辟或调用WebService的几种方式
Java开辟或调用WebService的几种方式


  
一.JDK自带的 JAX-WS 方式开辟WebService服务

1.服务端开辟与发布

  1. @WebService
  2. public interface JaxWsDemo {
  3.     String helloJaxWS(String userName);
  4. }
复制代码
  1. @WebService
  2. public class JaxWsDemoImpl implements JaxWsDemo {
  3.     @WebMethod
  4.     @WebResult(name = "jaxWSResult")
  5.     @Override
  6.     public String helloJaxWS(@WebParam(name = "userName")String userName) {
  7.         return "hello," + userName + "This is a Web Service developed through JAX-WS";
  8.     }
  9. }
复制代码
  1. public class JAXWSPublishMain {
  2.     public static void main(String[] args) {
  3.         String address = "http://127.0.0.1:8888/JaxWSTest";
  4.         Endpoint.publish(address, new JaxWsDemoImpl());
  5.         System.out.println("WebService 服务已发布!");
  6.     }
  7. }
复制代码
打开欣赏器输入http://127.0.0.1:8888/JaxWSTest?wsdl访问,如下面内容

截图内容1
  1. <!--
  2. Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e.
  3. -->
  4. <!--
  5. Generated by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e.
  6. -->
  7. <definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://wsimpl.jaxws/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://wsimpl.jaxws/" name="JaxWsDemoImplService">
  8. <types>
  9. <xsd:schema>
  10. <xsd:import namespace="http://wsimpl.jaxws/" schemaLocation="http://127.0.0.1:8888/JaxWSTest?xsd=1"/>
  11. </xsd:schema>
  12. </types>
  13. <message name="helloJaxWS">
  14. <part name="parameters" element="tns:helloJaxWS"/>
  15. </message>
  16. <message name="helloJaxWSResponse">
  17. <part name="parameters" element="tns:helloJaxWSResponse"/>
  18. </message>
  19. <portType name="JaxWsDemoImpl">
  20. <operation name="helloJaxWS">
  21. <input wsam:Action="http://wsimpl.jaxws/JaxWsDemoImpl/helloJaxWSRequest" message="tns:helloJaxWS"/>
  22. <output wsam:Action="http://wsimpl.jaxws/JaxWsDemoImpl/helloJaxWSResponse" message="tns:helloJaxWSResponse"/>
  23. </operation>
  24. </portType>
  25. <binding name="JaxWsDemoImplPortBinding" type="tns:JaxWsDemoImpl">
  26. <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
  27. <operation name="helloJaxWS">
  28. <soap:operation soapAction=""/>
  29. <input>
  30. <soap:body use="literal"/>
  31. </input>
  32. <output>
  33. <soap:body use="literal"/>
  34. </output>
  35. </operation>
  36. </binding>
  37. <service name="JaxWsDemoImplService">
  38. <port name="JaxWsDemoImplPort" binding="tns:JaxWsDemoImplPortBinding">
  39. <soap:address location="http://127.0.0.1:8888/JaxWSTest"/>
  40. </port>
  41. </service>
  42. </definitions>
复制代码
欣赏器中输入wsdl文档中的 http://127.0.0.1:8888/JaxWSTest?xsd=1可查看绑定的参数等信息看如下图:

截图内容2
  1. <!--
  2. Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e.
  3. -->
  4. <xs:schema xmlns:tns="http://wsimpl.jaxws/" xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0" targetNamespace="http://wsimpl.jaxws/">
  5. <xs:element name="helloJaxWS" type="tns:helloJaxWS"/>
  6. <xs:element name="helloJaxWSResponse" type="tns:helloJaxWSResponse"/>
  7. <xs:complexType name="helloJaxWS">
  8. <xs:sequence>
  9. <xs:element name="userName" type="xs:string" minOccurs="0"/>
  10. </xs:sequence>
  11. </xs:complexType>
  12. <xs:complexType name="helloJaxWSResponse">
  13. <xs:sequence>
  14. <xs:element name="jaxWSResult" type="xs:string" minOccurs="0"/>
  15. </xs:sequence>
  16. </xs:complexType>
  17. </xs:schema>
复制代码
  1. -encoding : 指定编码格式
  2. -keep:是否生成java源文件
  3. -d:指定.class文件的输出目录
  4. -s:指定.java文件的输出目录,   此目录必须存在
  5. -p:定义生成类的包名,不定义的话有默认包名
  6. -verbose:在控制台显示输出信息
  7. -b:指定jaxws/jaxb绑定文件或额外的schemas
  8. -extension:使用扩展来支持SOAP1.2
  9. # 举例
  10. wsimport -encoding utf-8 -keep -d D:\temp -p com.lawyer.user -verbose http://IP:port/serverName?wsdl
复制代码
2.客户端开辟与测试

切换到要生成客户端源码的路径下,如下:
  1. cd F:\SpringBootProjects\webServiceDemo\jwsDemo\src\main\java\demoOne\client>
复制代码
根据wsdl文档地点生成源码信息:
  1. F:\SpringBootProjects\webServiceDemo\jwsDemo\src\main\java\demoOne\client>
  2. wsimport -d F:\SpringBootProjects\webServiceDemo\jwsDemo\src\main\java\demoOne\client
  3. -keep -verbose http://127.0.0.1:8888/JaxWSTest?wsdl
复制代码
参数阐明:
  1. wsimport : 导入命令,如果使用cxf就换成 wsdl2java  命令
  2. -d [源码位置]      : 指定要生成的源码的目录,不指定则默认在哪个目录打开的cmd窗口,就生在那个目录下
  3. -keep : 是否生成*.java的源文件,写了此参数则直接生成*.java与*.class文件,不写此参数则只有*.class文件
  4. -verbose : 显示文件生成过程中的详细信息
  5. -p [包名]: 指定要生成在哪个包下,不指定生成时取默认
复制代码
  1. package demoOne.client;
  2. import demoone.JaxWsDemoImplService;
  3. /**
  4. * Created by IntelliJ IDEA.
  5. * User: jinshengyuan
  6. * Date: 2019-03-13
  7. * Time: 10:34
  8. * description: 客户端测试
  9. **/
  10. public class ClientTest {
  11.     public static void main(String[] args) {
  12.         demoone.JaxWsDemoImplService implService = new JaxWsDemoImplService();
  13.        demoone.JaxWsDemoImpl jaxWsDemo = (demoone.JaxWsDemoImpl)implService.getJaxWsDemoImplPort();
  14.        String aa = jaxWsDemo.helloJaxWS("Tom ");
  15.         System.out.println("调用WebService执行结果:"+aa);
  16.     }
  17. }
复制代码
执行结果:
  1. 调用WebService执行结果:hello,Tom This is a Web Service developed through JAX-WS
复制代码
二.Axis1.4调用.Net返回值为DataSet类型的WebService接口

1.相干阐明

2. Axis1.4客户端WebService服务

1.Axis1.4下载


4.maven环境的话,在pom.xml中添加下面的依赖即可
  1. <!--Axis1.4 及其依赖 begin-->
  2.         <!-- https://mvnrepository.com/artifact/org.apache.axis/axis -->
  3.         <dependency>
  4.             <groupId>org.apache.axis</groupId>
  5.             <artifactId>axis</artifactId>
  6.             <version>1.4</version>
  7.         </dependency>
  8.         <!-- https://mvnrepository.com/artifact/jaxrpc/jaxrpc -->
  9.         <!-- https://mvnrepository.com/artifact/axis/axis-jaxrpc -->
  10.         <dependency>
  11.             <groupId>axis</groupId>
  12.             <artifactId>axis-jaxrpc</artifactId>
  13.             <version>1.4</version>
  14.         </dependency>
  15.         <!-- https://mvnrepository.com/artifact/axis/axis-ant -->
  16.         <dependency>
  17.             <groupId>axis</groupId>
  18.             <artifactId>axis-ant</artifactId>
  19.             <version>1.4</version>
  20.         </dependency>
  21.         <!-- https://mvnrepository.com/artifact/axis/axis-saaj -->
  22.         <dependency>
  23.             <groupId>axis</groupId>
  24.             <artifactId>axis-saaj</artifactId>
  25.             <version>1.4</version>
  26.         </dependency>
  27.         <!-- https://mvnrepository.com/artifact/wsdl4j/wsdl4j -->
  28.         <dependency>
  29.             <groupId>wsdl4j</groupId>
  30.             <artifactId>wsdl4j</artifactId>
  31.             <version>1.6.3</version>
  32.         </dependency>
  33.         <!-- https://mvnrepository.com/artifact/commons-discovery/commons-discovery -->
  34.         <dependency>
  35.             <groupId>commons-discovery</groupId>
  36.             <artifactId>commons-discovery</artifactId>
  37.             <version>0.5</version>
  38.         </dependency>
  39.         <!--Axis1.4 及其依赖 end-->
  40.                 <!-- 引入dom4j 解析数据时用-->
  41. <!-- https://mvnrepository.com/artifact/org.dom4j/dom4j -->
  42.         <dependency>
  43.             <groupId>org.dom4j</groupId>
  44.             <artifactId>dom4j</artifactId>
  45.             <version>2.1.1</version>
  46.         </dependency>
复制代码
2.WebService服务接口地点及方法

3.编写调用WebService服务的方法及数据解析

  1. package com.yuan;
  2. import org.apache.axis.client.Call;
  3. import org.apache.axis.client.Service;
  4. import org.apache.axis.encoding.XMLType;
  5. import org.apache.axis.message.MessageElement;
  6. import org.apache.axis.types.Schema;
  7. import org.dom4j.Document;
  8. import org.dom4j.DocumentException;
  9. import org.dom4j.DocumentHelper;
  10. import org.dom4j.Element;
  11. import org.junit.Test;
  12. import javax.xml.namespace.QName;
  13. import java.net.URL;
  14. import java.util.Iterator;
  15. import java.util.List;
  16. /**
  17. * Created by IntelliJ IDEA.
  18. * User: jinshengyuan
  19. * Date: 2019-01-15
  20. * Time: 15:13
  21. * description:
  22. **/
  23. public class Axis1_Client {
  24.     /**
  25.      * 使用dom4j解析数据
  26.      */
  27.     @Test
  28.     public void axisWSInvoke(){
  29.         String dataSetDataStr = axisInvokeNetDataSetData();
  30.         //System.out.println(dataSetDataStr);
  31.         if(dataSetDataStr != null){
  32.             try {
  33.                 Document doc = DocumentHelper.parseText(dataSetDataStr);// 将字符串转为XML
  34.                 Element root = doc.getRootElement();// 获取根节点
  35.                 Iterator iterator =  root.elementIterator("Zone");//迭代节点
  36.                 String id,zone;
  37.                 while(iterator.hasNext()){
  38.                   Element element = (Element) iterator.next();
  39.                   id = element.elementTextTrim("ID");//取出Zone节点下的ID元素的值
  40.                   zone = element.elementTextTrim("Zone");//取出Zone节点下的Zone元素的值
  41.                     System.out.println("Id:"+id+"=============================Zone:"+zone);
  42.                 }
  43.             } catch (DocumentException e) {
  44.                 e.printStackTrace();
  45.             }
  46.         }
  47.     }
  48.     /**
  49.      * 调用.Net写的返回值为DataSet类型的WebService服务
  50.      * @return
  51.      */
  52.     public String axisInvokeNetDataSetData(){
  53.         Service service = new Service();
  54.         String strXml = null;
  55.         Call call = null;
  56.         try {
  57.             call = (Call) service.createCall();
  58.             call.setTargetEndpointAddress(new URL("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx"));//WSURL,注意不要带?wsdl
  59.             //调用方法方法前设置相关参数
  60.             call.setOperationName(new QName("http://WebXml.com.cn/", "getSupportDataSet"));
  61.             call.setReturnType(XMLType.XSD_SCHEMA);//返回类型,这里一定要传入 XMLType.XSD_SCHEMA 类型
  62.             call.setUseSOAPAction(true);
  63.             call.setSOAPActionURI("http://WebXml.com.cn/getSupportDataSet");//soapAction
  64.             Object obj = call.invoke((Object[]) null);
  65.             Schema schema = (Schema) obj;
  66.             MessageElement[] messageElements = schema.get_any();
  67.             List messageHead = messageElements[0].getChildren();//消息头,DataSet对象
  68.             List messageBody = messageElements[1].getChildren();//消息体信息,DataSet对象,最终需要解析的数据
  69.             if (messageBody.size() > 0) {
  70.                 String head = messageHead.get(0).toString();//消息头,DataSet对象
  71.                 String diffgr = messageBody.get(0).toString();//消息体的字符串形式
  72.                 strXml = diffgr;
  73.                 System.out.println("head:\n"+head);
  74.                 System.out.println("diffgr:\n" + diffgr);
  75.             }
  76.         } catch (Exception e) {
  77.             e.printStackTrace();
  78.         }
  79.         return strXml;
  80.     }
  81. }
复制代码
  1. Id:1=============================Zone:直辖市
  2. Id:2=============================Zone:特别行政区
  3. Id:3=============================Zone:黑龙江
  4. Id:4=============================Zone:吉林
  5. Id:5=============================Zone:辽宁
  6. Id:6=============================Zone:内蒙古
  7. Id:7=============================Zone:河北
  8. Id:8=============================Zone:河南
  9. Id:9=============================Zone:山东
  10. Id:10=============================Zone:山西
  11. Id:11=============================Zone:江苏
  12. Id:12=============================Zone:安徽
  13. Id:13=============================Zone:陕西
  14. Id:14=============================Zone:宁夏
  15. Id:15=============================Zone:甘肃
  16. Id:16=============================Zone:青海
  17. Id:17=============================Zone:湖北
  18. Id:18=============================Zone:湖南
  19. Id:19=============================Zone:浙江
  20. Id:20=============================Zone:江西
  21. Id:21=============================Zone:福建
  22. Id:22=============================Zone:贵州
  23. Id:23=============================Zone:四川
  24. Id:24=============================Zone:广东
  25. Id:25=============================Zone:广西
  26. Id:26=============================Zone:云南
  27. Id:27=============================Zone:海南
  28. Id:28=============================Zone:新疆
  29. Id:29=============================Zone:西藏
  30. Id:30=============================Zone:台湾
  31. Id:31=============================Zone:亚洲
  32. Id:32=============================Zone:欧洲
  33. Id:33=============================Zone:非洲
  34. Id:34=============================Zone:北美洲
  35. Id:35=============================Zone:南美洲
  36. Id:36=============================Zone:大洋洲
复制代码
三. CXF 开辟WebService接口

1. jax-ws实现

   场景:CXF结合Spring实现发布与调用简单的WebService
  

  1. package com.ssm.webservice;
  2. import javax.jws.WebMethod;
  3. import javax.jws.WebParam;
  4. import javax.jws.WebResult;
  5. import javax.jws.WebService;
  6. /**
  7. * Created by IntelliJ IDEA.
  8. * User: jinshengyuan
  9. * Date: 2018-11-09
  10. * Time: 9:04
  11. * description:
  12. **/
  13. @WebService
  14. public interface Hello {
  15.      @WebMethod
  16.      @WebResult(name = "result") String sayHello(@WebParam(name = "name") String name);
  17. }
复制代码
  1. package com.ssm.webservice.impl;
  2. import com.ssm.dao.sysManagement.ComLogMapper;
  3. import com.ssm.model.ComLog;
  4. import com.ssm.service.sysManagement.ComLogService;
  5. import com.ssm.utils.CommonsUtil;
  6. import com.ssm.webservice.Hello;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Component;
  9. import java.text.SimpleDateFormat;
  10. import java.util.Date;
  11. /**
  12. * Created by IntelliJ IDEA.
  13. * User: jinshengyuan
  14. * Date: 2018-11-09
  15. * Time: 9:06
  16. * description:
  17. **/
  18. public class HelloImpl implements Hello {
  19.     //这里跟controller中调用Service一样,使用@Autowired注解自动注入service
  20.     @Autowired
  21.     ComLogService comLogService;
  22.     @Override
  23.     public String sayHello(String name) {
  24.         //从数据库中获取当前系统日期
  25.         Date date = comLogService.getCurrentDatetime();
  26.         String currentDateTime = null;
  27.         if(date != null){
  28.             SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  29.             currentDateTime = dateFormat.format(date);
  30.             System.out.println("系统日期:"+currentDateTime);
  31.         }
  32.         return "hello," + name + ",当前时间为:"+currentDateTime;
  33.     }
  34. }
复制代码

  1. <!-- 引入CXF配置文件,低版本(3.0以下)还需引入其他两个文件 -->
  2.     <import resource="classpath:META-INF/cxf/cxf.xml" />
  3.     <!-- 配置方式1   注意:serviceClass为接口类并非接口的实现类 -->
  4.     <jaxws:server serviceClass="com.ssm.webservice.Hello" address="/webServiceTestA"></jaxws:server>
  5.     <!--访问地址:http://localhost:8080/ssm/webService/webServiceTestA?wsdl-->
  6.     <!-- 配置方式2    注意:implementor为接口的具体实现类,与springmvc整合时,推荐使用这种方式,如果使用配置方式1,则会在访问时,提示如下错误:
  7.      org.apache.cxf.interceptor.Fault: Could not instantiate service class com.ssm.webservice.Hello because it is an interface.
  8.      -->
  9.     <jaxws:endpoint implementor="com.ssm.webservice.impl.HelloImpl" address="/webServiceTest"></jaxws:endpoint>
  10.     <!--访问地址:http://localhost:8080/ssm/webService/webServiceTest?wsdl-->
复制代码
  1. <!-- cxf服务启动servlet -->
  2.     <servlet>
  3.         <servlet-name>CXFServlet</servlet-name>
  4.         <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  5.     </servlet>
  6.     <servlet-mapping>
  7.         <servlet-name>CXFServlet</servlet-name>
  8.         <!--工程名(ssm)后面紧跟的 url-->
  9.         <url-pattern>/webService/*</url-pattern>
  10.     </servlet-mapping>
复制代码

2. CXF-RESTFul服务实现


   JAX-RS是Java提供用于开辟RESTful Web服务基于注解(annotation)的API。JAX-RS旨在定义一个同一的规范,使得Java程序员可以使用一套固定的接口来开辟REST应用,避免了依赖第三方框架。同时JAX-RS使用POJO编程模型和基于注解的设置并集成JAXB,可以有效缩短REST应用的开辟周期。JAX-RS只定义RESTful API,详细实现由第三方提供,如Jersey、Apache CXF等。
  JAX-RS包含近五十多个接口、注解和抽象类:

JAX-RS常用注解:


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4