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

标题: WebService使用 [打印本页]

作者: 干翻全岛蛙蛙    时间: 2024-6-18 18:06
标题: WebService使用
java发布WebService

   普通maven项目,使用原生jdk发布webservice
  1.pom

  1. <dependencies>
  2.     <dependency>
  3.       <groupId>junit</groupId>
  4.       <artifactId>junit</artifactId>
  5.       <version>3.8.1</version>
  6.       <scope>test</scope>
  7.     </dependency>
  8.     <dependency>
  9.     <groupId>com.alibaba</groupId>
  10.     <artifactId>fastjson</artifactId>
  11.     <version>1.2.76</version>
  12.         </dependency>
  13.        
  14.   </dependencies>
复制代码
2.接口

  1. import javax.jws.WebService;
  2. import javax.jws.WebParam;
  3. /**
  4. * 对外发布服务的接口       
  5. * */
  6. @WebService//(targetNamespace = "http://wsImpl.com/")
  7. public interface HelloWs {
  8.        
  9.         public String sayHello(@WebParam(name="arg0")String name);
  10. }
复制代码
3.实现类

  1. import java.util.HashMap;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.ws.HelloWs;
  4. public class HelloWsImpl implements HelloWs{
  5.         public String sayHello(String name) {
  6.             String jsonStr = json();
  7.                 System.out.print(name);
  8.                 return jsonStr;
  9.         }
  10.        
  11.        
  12.         //将map变成json并通过报文返回
  13.         public String mapJson(){
  14.                 HashMap<String, Object> zhangsan = new HashMap<String, Object>();
  15.         zhangsan.put("name", "张三");
  16.         zhangsan.put("age", 18.4);
  17.         zhangsan.put("birthday", "1900-20-03");
  18.         zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});
  19.         zhangsan.put("null", null);
  20.         zhangsan.put("house", false);
  21.         //System.out.println(new JSONObject(zhangsan).toString());
  22.         String jsonStr = new JSONObject(zhangsan).toString();
  23.         // TODO Auto-generated method stub
  24.         return jsonStr;
  25.         }
  26.        
  27.         //原生json并通过报文返回
  28.         public String json(){
  29.                 JSONObject zhangsan = new JSONObject();
  30.                 zhangsan.put("name", "张三");
  31.             zhangsan.put("age", 18.4);
  32.             zhangsan.put("birthday", "1900-20-03");
  33.             zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});
  34.             zhangsan.put("null", null);
  35.             zhangsan.put("house", false);
  36.             return zhangsan.toString();   
  37.         }
  38. }
复制代码
4.发布类

   主方法运行后,直接在浏览器访问http://ip:8080/ws/hello?wsdl
  1. import javax.xml.ws.Endpoint;
  2. import com.wsImpl.HelloWsImpl;
  3. public class Service {
  4.         public static void main(String[] args) {
  5.                 //设置服务地址,换成你的ip
  6.                 Endpoint.publish("http://10.10.150.20:8080/ws/hello",new HelloWsImpl());
  7.                
  8.                 System.out.println("发布WS服务成功");
  9.         }
  10. }
复制代码
5.调用方法

  1. import java.io.IOException;
  2. import java.net.URL;
  3. import javax.xml.namespace.QName;
  4. import javax.xml.ws.Service;
  5. import com.ws.HelloWs;
  6. public class ProtoCall {
  7.     public static void main(String[] args) throws IOException {
  8.         //创建WSDL地址,不是服务地址
  9.         URL url = new URL("http://10.10.150.20:8080/ws/hello?wsdl");
  10.         /**
  11.          * QName是XML元素的限定名称,是组成XML的最基本的要素
  12.          * */
  13.         //创建服务名称
  14.         //1.namespaceURI - 命名空间地址
  15.         //2.localPart - 服务名称,wsdl中的name,不是@WebService注解中的name
  16.         QName qname = new QName("http://wsImpl.com/", "HelloWsImplService");
  17.         //Service创建视图
  18.         //参数:
  19.         //1.wsdlDocumentLocation - 使用说明书地址
  20.         //2.serviceName - 服务名称
  21.         Service service = Service.create(url, qname);
  22.         //获取实现类
  23.         HelloWs mobileCodeWSSoap = service.getPort(HelloWs.class);
  24.         //调用查询方法
  25.         String result = mobileCodeWSSoap.sayHello("188888888");
  26.         System.out.println(result);
  27.     }
  28. }
复制代码

CXF发布WebService

   普通maven项目,使用apache.cxf发布webservice
  1.pom

  1. <dependencies>
  2.     <dependency>
  3.       <groupId>junit</groupId>
  4.       <artifactId>junit</artifactId>
  5.       <version>3.8.1</version>
  6.       <scope>test</scope>
  7.     </dependency>
  8.    
  9.       <dependency>
  10.             <groupId>org.apache.cxf</groupId>
  11.             <artifactId>cxf-rt-frontend-jaxws</artifactId>
  12.             <version>3.4.3</version>
  13.         </dependency>
  14.    
  15.     <dependency><!-- 内置jetty web服务器 -->
  16.             <groupId>org.apache.cxf</groupId>
  17.             <artifactId>cxf-rt-transports-http-jetty</artifactId>
  18.             <version>3.4.3</version>
  19.             <scope>test</scope>
  20.         </dependency>
  21.     <dependency>
  22.     <groupId>com.alibaba</groupId>
  23.     <artifactId>fastjson</artifactId>
  24.     <version>1.2.76</version>
  25. </dependency>
  26.   </dependencies>
复制代码
2.接口

  1. import javax.jws.WebService;
  2. import javax.jws.WebParam;
  3. /**
  4. * 对外发布服务的接口       
  5. * */
  6. @WebService//(targetNamespace = "http://wsImpl.com/")
  7. public interface HelloWs {
  8.        
  9.         public String sayHello(@WebParam(name="arg0")String name);
  10. }
复制代码
3.实现类

  1. import java.util.HashMap;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.ws.HelloWs;
  4. public class HelloWsImpl implements HelloWs{
  5.         public String sayHello(String name) {
  6.             String jsonStr = json();
  7.                 System.out.print(name);
  8.                 return jsonStr;
  9.         }
  10.        
  11.        
  12.         //将map变成json并通过电文返回
  13.         public String mapJson(){
  14.                 HashMap<String, Object> zhangsan = new HashMap<String, Object>();
  15.         zhangsan.put("name", "张三");
  16.         zhangsan.put("age", 18.4);
  17.         zhangsan.put("birthday", "1900-20-03");
  18.         zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});
  19.         zhangsan.put("null", null);
  20.         zhangsan.put("house", false);
  21.         //System.out.println(new JSONObject(zhangsan).toString());
  22.         String jsonStr = new JSONObject(zhangsan).toString();
  23.         // TODO Auto-generated method stub
  24.         return jsonStr;
  25.         }
  26.        
  27.         //原生json并通过电文返回
  28.         public String json(){
  29.                 JSONObject zhangsan = new JSONObject();
  30.                 zhangsan.put("name", "张三");
  31.             zhangsan.put("age", 18.4);
  32.             zhangsan.put("birthday", "1900-20-03");
  33.             zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});
  34.             zhangsan.put("null", null);
  35.             zhangsan.put("house", false);
  36.             return zhangsan.toString();   
  37.         }
  38. }
复制代码
4.发布类

   主方法运行后,直接在浏览器访问http://ip:8080/ws/hello?wsdl
  1. import org.apache.cxf.interceptor.LoggingInInterceptor;
  2. import org.apache.cxf.interceptor.LoggingOutInterceptor;
  3. import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
  4. import com.wsImpl.HelloWsImpl;
  5. public class Service {
  6.         public static void main(String[] args) {
  7.         
  8.          /**
  9.                 EndpointImpl发布方式
  10.         */
  11.                 //EndpointImpl publish = (EndpointImpl) Endpoint.publish("http://10.10.150.20:8080/ws/hello",new HelloWsImpl());
  12.                 //publish.getOutInterceptors().add(new LoggingOutInterceptor());
  13.                 //publish.getInInterceptors().add(new LoggingInInterceptor());
  14.                
  15.         /**
  16.                 工厂发布方式
  17.         */
  18.         //发布服务的工厂
  19.                 JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
  20.                
  21.                 //设置服务地址,换成你的ip
  22.                 factory.setAddress("http://10.10.150.20:8080/ws/hello");
  23.                
  24.                 //设置服务类
  25.                 factory.setServiceBean(new HelloWsImpl());
  26.                
  27.                 //添加日志输入输出拦截器
  28.                 factory.getInInterceptors().add(new LoggingInInterceptor());  
  29.         factory.getOutInterceptors().add(new LoggingOutInterceptor());
  30.                
  31.                 //发布服务
  32.                 factory.create();
  33.                
  34.                 System.out.println("发布WS服务成功");
  35.         }
  36. }
复制代码
5.调用方法

  1. import java.io.IOException;
  2. import java.net.URL;
  3. import javax.xml.namespace.QName;
  4. import javax.xml.ws.Service;
  5. import com.ws.HelloWs;
  6. public class ProtoCall {
  7.     public static void main(String[] args) throws IOException {
  8.         //创建WSDL地址,不是服务地址
  9.         URL url = new URL("http://10.10.150.20:8080/ws/hello?wsdl");
  10.         /**
  11.          * QName是XML元素的限定名称,是组成XML的最基本的要素
  12.          * */
  13.         //创建服务名称
  14.         //1.namespaceURI - 命名空间地址
  15.         //2.localPart - 服务名称,wsdl中的name,不是@WebService注解中的name
  16.         QName qname = new QName("http://wsImpl.com/", "HelloWsImplService");
  17.         //Service创建视图
  18.         //参数:
  19.         //1.wsdlDocumentLocation - 使用说明书地址
  20.         //2.serviceName - 服务名称
  21.         Service service = Service.create(url, qname);
  22.         //获取实现类
  23.         HelloWs mobileCodeWSSoap = service.getPort(HelloWs.class);
  24.         //调用查询方法
  25.         String result = mobileCodeWSSoap.sayHello("188888888");
  26.         System.out.println(result);
  27.     }
  28. }
复制代码

整合SpringBoot发布及调用

1.pom依赖

  1. <dependencies>
  2.         <!-- 核心启动器 -->
  3.         <dependency>
  4.             <groupId>org.springframework.boot</groupId>
  5.             <artifactId>spring-boot-starter</artifactId>
  6.         </dependency>
  7.         <!-- web启动器 -->
  8.         <dependency>
  9.             <groupId>org.springframework.boot</groupId>
  10.             <artifactId>spring-boot-starter-web</artifactId>
  11.         </dependency>
  12.         <!-- webService-->
  13.         <dependency>
  14.             <groupId>org.springframework.boot</groupId>
  15.             <artifactId>spring-boot-starter-web-services</artifactId>
  16.         </dependency>
  17.         <!-- CXF webservice -->
  18.         <dependency>
  19.             <groupId>org.apache.cxf</groupId>
  20.             <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
  21.             <version>3.2.1</version>
  22.         </dependency>
  23.         <dependency>
  24.             <groupId>org.apache.cxf</groupId>
  25.             <artifactId>cxf-rt-transports-http</artifactId>
  26.             <version>3.2.1</version>
  27.         </dependency>
  28.         <dependency>
  29.             <groupId>org.apache.cxf</groupId>
  30.             <artifactId>cxf-rt-ws-security</artifactId>
  31.             <version>3.2.1</version>
  32.         </dependency>
  33.         <!-- CXF webservice -->
  34.         <!-- https://mvnrepository.com/artifact/commons-discovery/commons-discovery -->
  35.         <dependency>
  36.             <groupId>wsdl4j</groupId>
  37.             <artifactId>wsdl4j</artifactId>
  38.             <version>1.6.3</version>
  39.         </dependency>
  40.         <!-- Restful接口依赖,用于rest风格接口 -->
  41.         <dependency>
  42.             <groupId>org.apache.cxf</groupId>
  43.             <artifactId>cxf-spring-boot-starter-jaxrs</artifactId>
  44.             <version>3.1.12</version>
  45.         </dependency>
  46.         <dependency>
  47.             <groupId>org.wso2.apache.httpcomponents</groupId>
  48.             <artifactId>httpclient</artifactId>
  49.             <version>4.3.1.wso2v1</version>
  50.         </dependency>
  51.         <!-- https://mvnrepository.com/artifact/org.apache.axis/axis -->
  52.         <dependency>
  53.             <groupId>org.apache.axis</groupId>
  54.             <artifactId>axis</artifactId>
  55.             <version>1.4</version>
  56.         </dependency>
  57.         <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
  58.         <dependency>
  59.             <groupId>commons-httpclient</groupId>
  60.             <artifactId>commons-httpclient</artifactId>
  61.             <version>3.1</version>
  62.         </dependency>
  63.         <!-- https://mvnrepository.com/artifact/javax.xml/jaxrpc -->
  64.         <dependency>
  65.             <groupId>javax.xml</groupId>
  66.             <artifactId>jaxrpc</artifactId>
  67.             <version>1.1</version>
  68.         </dependency>
  69.         <dependency>
  70.             <groupId>commons-logging</groupId>
  71.             <artifactId>commons-logging</artifactId>
  72.             <version>1.0.4</version>
  73.         </dependency>
  74.         <!-- https://mvnrepository.com/artifact/commons-discovery/commons-discovery -->
  75.         <dependency>
  76.             <groupId>commons-discovery</groupId>
  77.             <artifactId>commons-discovery</artifactId>
  78.             <version>0.5</version>
  79.         </dependency>
  80.         <!-- 阿里JSON解析器 -->
  81.         <dependency>
  82.             <groupId>com.alibaba</groupId>
  83.             <artifactId>fastjson</artifactId>
  84.             <version>1.2.47</version>
  85.         </dependency>
  86.         <dependency>
  87.             <groupId>org.hibernate</groupId>
  88.             <artifactId>hibernate-validator</artifactId>
  89.             <version>6.0.18.Final</version>
  90.         </dependency>
  91.         <dependency>
  92.             <groupId>junit</groupId>
  93.             <artifactId>junit</artifactId>
  94.             <scope>test</scope>
  95.         </dependency>
  96.     </dependencies>
复制代码
2.创建接口及实现类

   接口
  @WebService: 标记此接口为WebService接口;name为接口名称,targetNamespace为名称空间,可以自定义;
@WebMethod: 标记方法为WebService接口中的方法
@WebParam: 标记参数为WebService接口中方法参数,可限定名称(name = “abdc”),不限定默以为方法参数变量名
  1. import javax.jws.WebMethod;
  2. import javax.jws.WebParam;
  3. import javax.jws.WebService;
  4. import javax.xml.ws.BindingType;
  5. import javax.xml.ws.soap.SOAPBinding;
  6. @WebService(name = "ServerServiceDemo", targetNamespace = "http://server.webservice.example.com")
  7. //@BindingType(value = SOAPBinding.SOAP12HTTP_BINDING)//将SOAP协议定义为1.2 Eclipse自带的WebService Brower只能解析soap1.1的协议,服务器端最好使用高版本的协议
  8. public interface ServerServiceDemo {
  9.     @WebMethod
  10.     String emrService(@WebParam String data);
  11. }
复制代码
  实现类
  @WebService: 标记此接口为WebService接口;name为接口名称,targetNamespace为名称空间,可以自定义;endpointInterface为此类实现接口的全路径
@WebParam: 标记参数为WebService接口中方法参数,可限定名称(name = “abdc”),不限定默以为方法参数变量名
  1. import com.alibaba.fastjson.JSONObject;
  2. import com.demo.axisDemo.service.ServerServiceDemo;
  3. import org.springframework.stereotype.Component;
  4. import javax.jws.WebParam;
  5. import javax.jws.WebService;
  6. @Component
  7. @WebService(name = "ServerServiceDemo", targetNamespace = "http://server.webservice.example.com",
  8.         endpointInterface = "com.demo.axisDemo.service.ServerServiceDemo")
  9. public class ServerServiceDemoImpl implements ServerServiceDemo {
  10.     @Override
  11.     public String emrService(@WebParam String data) {
  12.         if (null == data || "".equals(data.trim())) {
  13.             return "传入的参数为空";
  14.         }
  15.         System.out.println(data + "     -------------------------");
  16.         return "服务端返回 调用成功:" + data;
  17.     }
  18. }
复制代码
3.编写配置类

  1. @Configuration
  2. public class WebServiceConfig {
  3.        
  4.         /**
  5.           引入接口类
  6.         */
  7.     @Autowired
  8.     private ServerServiceDemo serverServiceDemo;
  9.        
  10.        
  11.        
  12.         /**
  13.      * Apache CXF 核心架构是以BUS为核心,整合其他组件。
  14.      * Bus是CXF的主干, 为共享资源提供一个可配置的场所,作用类似于Spring的ApplicationContext,这些共享资源包括
  15.      * WSDl管理器、绑定工厂等。通过对BUS进行扩展,可以方便地容纳自己的资源,或者替换现有的资源。默认Bus实现基于Spring架构,
  16.      * 通过依赖注入,在运行时将组件串联起来。BusFactory负责Bus的创建。默认的BusFactory是SpringBusFactory,对应于默认
  17.      * 的Bus实现。在构造过程中,SpringBusFactory会搜索META-INF/cxf(包含在 CXF 的jar中)下的所有bean配置文件。
  18.      * 根据这些配置文件构建一个ApplicationContext。开发者也可以提供自己的配置文件来定制Bus。
  19.      */
  20.     @Bean(name = Bus.DEFAULT_BUS_ID)
  21.     public SpringBus springBus() {
  22.         return new SpringBus();
  23.     }
  24.    
  25.    
  26.     /*
  27.      * 此方法作用是改变项目中服务名的前缀名
  28.      * 此方法被注释后, 即不改变前缀名(默认是services), wsdl访问地址为 http://127.0.0.1:8080/services/ws/api?wsdl
  29.      * 去掉注释后wsdl访问地址为:http://127.0.0.1:8080/soap/ws/api?wsdl
  30.     //@Bean
  31.     //public ServletRegistrationBean dispatcherServlet() {
  32.     //    return new ServletRegistrationBean(new CXFServlet(), "/soap/*");
  33.     //}
  34.    
  35.    
  36.    
  37.     /**
  38.      * 此处的EndpointImpl构造方法源码调用了JaxWsServiceFactoryBean及WebServiceFeature,
  39.      * 即在bus中开启webservice功能,并通过JaxWsServiceFactoryBean获取一个具体服务
  40.      *
  41.      * EndpointImpl端点对象,可以将其作用理解为连接bus与java WS服务
  42.      * WebServiceFeature 用于表示可以为 Web 服务启用或禁用的功能。
  43.      * */
  44.     @Bean
  45.     public Endpoint endpoint() {
  46.         EndpointImpl endpoint = new EndpointImpl(springBus(), serverServiceDemo);//363
  47.         endpoint.publish("/ws/api");
  48.         return endpoint;   
  49.     }
  50.    
  51.    
  52. }
复制代码
4.客户端调用

   Axis调用
  1. import org.apache.axis.client.Call;
  2. import org.apache.axis.client.Service;
  3. import org.apache.axis.encoding.XMLType;
  4. import org.apache.axis.message.SOAPHeaderElement;
  5. import org.apache.cxf.configuration.security.AuthorizationPolicy;
  6. import org.apache.cxf.helpers.DOMUtils;
  7. import javax.xml.namespace.QName;
  8. import javax.xml.rpc.ParameterMode;
  9. import java.net.URL;
  10. public class CallUtiles {
  11.         //接口地址
  12.     private static String publishUrl = "http://localhost:8080/services/ws/api?wsdl";
  13.     //wsdl中的targetNamespace
  14.     private static String nameSpaceURI = "http://server.webservice.example.com";
  15.    
  16.     public static String get(String userStr) throws Exception {
  17.         Service service = new Service();
  18.         Call call = (Call) service.createCall();
  19.         call.setTargetEndpointAddress(new URL(publishUrl));
  20.         
  21.         //指定接口路径,要调用的方法名
  22.         call.setOperationName(new QName(nameSpaceURI, "emrService"));
  23.         
  24.         //如果没用@WebParam(name="name")来表明参数名,则方法的入参是啥,这边就必须传一样的参数名才行。不然报错。
  25.         call.addParameter("arg0", XMLType.XSD_STRING, ParameterMode.IN);
  26.         
  27.         call.setReturnType(XMLType.XSD_STRING);
  28.         Object[] obj = new Object[]{userStr};
  29.         String result = (String) call.invoke(obj);
  30.         return result;
  31.     }
  32. }
复制代码
  java原生调用
  1. import com.demo.axisDemo.service.ServerServiceDemo;
  2. import java.io.IOException;
  3. import java.net.URL;
  4. import javax.xml.namespace.QName;
  5. import javax.xml.ws.Service;
  6. public class ProtoCall {
  7.     public static void main(String[] args) throws IOException {
  8.         //创建WSDL地址,不是服务地址
  9.         URL url = new URL("http://127.0.0.1:9088/api/Domain/Xinda-ESB/esb-ec2erp?wsdl");
  10.         /**
  11.          * QName是XML元素的限定名称,是组成XML的最基本的要素
  12.          * */
  13.         //创建服务名称
  14.         //1.namespaceURI - 命名空间地址
  15.         //2.localPart - 服务名称,wsdl中的name,不是@WebService注解中的name
  16.         QName qname = new QName("http://service.erp.esb.xinda.com/IDTIWSReceEC", "IDTIWSReceEC");
  17.         //Service创建视图
  18.         //参数:
  19.         //1.wsdlDocumentLocation - 使用说明书地址
  20.         //2.serviceName - 服务名称
  21.         Service service = Service.create(url, qname);
  22.         //获取实现类
  23.         ServerServiceDemo mobileCodeWSSoap = service.getPort(ServerServiceDemo.class);
  24.         //调用查询方法
  25.         String result = mobileCodeWSSoap.emrService("188888888");
  26.         System.out.println(result);
  27.     }
  28. }
复制代码
  下令工具调用
  1. cmd输入命令:wsdl2java -p com -d ../src -client -encoding utf-8  http://localhost:8080/admin/cxfService?wsdl
  2. 注意:wsdl地址必须与发布publish中的相同,执行后会在../src生成代码,直接使用实现类get方法调用
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




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