最近公司与一些大公司对接服务,使用的是老掉牙的web service协议的接口,其中遇到了不少的坑。在此将自己的经验描述一下,让各位后辈能学习到东西。。。
1:介绍webservice
Web Service是一个平台独立的,低耦合的,自包含的、基于可编程的web的应用程序,可使用开放的XML(标准通用标记语言下的一个子集)标准来描述、发布、发现、协调和配置这些应用程序,用于开发分布式的交互操作的应用程序。 [1]
Web Service技术, 能使得运行在不同机器上的不同应用无须借助附加的、专门的第三方软件或硬件, 就可相互交换数据或集成。依据Web Service规范实施的应用之间, 无论它们所使用的语言、 平台或内部协议是什么, 都可以相互交换数据。Web Service是自描述、 自包含的可用网络模块, 可以执行具体的业务功能。Web Service也很容易部署, 因为它们基于一些常规的产业标准以及已有的一些技术,诸如标准通用标记语言下的子集XML、HTTP。Web Service减少了应用接口的花费。Web Service为整个企业甚至多个组织之间的业务流程的集成提供了一个通用机制。– 来自百度百科
WebService网图
2:需求
2.1 需求1
公司的某个大公司客户,给了一份技术对接文档,是webservice协议的。然后给了一个wsdl文件;需要我们公司项目提供一个接口调用,需要按照大公司客户的需求文档的接口规范编写,我这边需要用springboot写一个订单接口并且具体响应信息。
2.2 需求2
大公司客户提供webservice协议的文档,需要我写一个接口去调用。基本的需求就是上面两个。但是webservice最重要的还是xml格式的组装。每家公司都已经有了各自的组装xml参数方式,只要稍微不一致,就会报错的。做这种接口的对接前,首先可下载一个soapui软件导入甲方给的wsdl文件,分析其请求xml数据,然后模拟调用该接口,相信大家已经会了。
使用soapui打开文件
这个大家肯定都是已经懂了。但是我要讲的干货肯定不是这些入门的玩意儿。 首先,当自己发布一个webservice接口,那么cxf会自己生成请求的“xml数据”,那么这个请求格式我们是不可控制的。大公司客户往往需要的不是自己自动生成的那种格式。所以需要有拦截器做自定义的数据组装
3:集成
公司项目springboot项目并且是Maven版本管理
需要导入maven依赖
<!-- web service -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.1.12</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>3.1.12</version>
</dependency>
<dependency>
<groupId>jakarta.jws</groupId>
<artifactId>jakarta.jws-api</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.13.1</version>
</dependency>
<!-- web service -->
见代码:
CxfConfig类
package com.efh.otms.admin.config;
import com.efh.otms.admin.ws.service.OtmsWebService;
import com.efh.otms.admin.ws.service.impl.OtmsWebServiceImpl;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.xml.ws.Endpoint;
/**
* @author Gaci
* @className CxfConfig
* @description cxf配置
* @date 2020/11/30 11:05
**/
@Configuration
public class CxfConfig {
@Bean
public ServletRegistrationBean createServletRegistrationBean() {
return new ServletRegistrationBean(new CXFServlet(), "/otmsWebService/*");
}
@Bean(name = Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
return new SpringBus();
}
@Bean
public OtmsWebService otmsWebService() {
return new OtmsWebServiceImpl();
}
@Bean
public Endpoint endpoint() {
EndpointImpl endpoint = new EndpointImpl(springBus(), otmsWebService());
endpoint.publish("/orderSyncReq")