1. 概述
WebService服务端是以远程接口为主的,在Java实现的WebService技术里主要依靠CXF开发框架,而这个CXF开发框架可以直接将接口发布成WebService。
CXF又分为JAX-WS和JAX-RS,JAX-WS是基于xml协议,而JAX-RS是基于Restful风格,两者的区别如下:
- RS基于Restful风格,WS基于SOAP的XML协议
- RS比WS传输的数据更少,效率更高
- WS只能传输XML数据,RS可以传输XML,也可以传输JSON
参考:
https://blog.csdn.net/liu320yj/article/details/121740367
https://www.cnblogs.com/myitnews/p/12370308.html
https://juejin.cn/post/6872881983937069063
此处讲解JAX-WS
2. 开发
2.1. maven依赖
<!--WebService-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<!-- CXF webservice -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxws</artifactId>
<version>3.4.5</version>
</dependency>
2.2. 新建实体类
/**
* @Author:wangdi
* @Date:2023/4/23 14:04
* @Des: UserInfo
*/
@Data
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
@XmlRootElement
@Accessors(chain = true)
public class UserInfo implements Serializable {
private static final long serialVersionUID = -5352429333001227976L;
private Long id;
private String username;
private String password;
}
2.3. 新建接口
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
/**
* @Author:wangdi
* @Date:2023/4/23 14:05
* @Des: UserInfoService
*/
@WebService(name = "userInfoService", targetNamespace = "http://server.webservice.gtp.sinotrans.com")
public interface UserInfoService {
@WebMethod(operationName = "saveUserInfo")
void saveUserInfo(@WebParam(name = "userInfo") UserInfo userInfo);
@WebMethod
UserInfo getUserInfoById(@WebParam(name = "id") Long id);
}
2.4. [服务端开发] 接口实现类
import com.sinotrans.framework.common.utils.JsonUtil;
import com.sinotrans.gtp.entity.UserInfo;
import com.sinotrans.gtp.webservice.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.jws.WebService;
/**
* @Author:wangdi
* @Date:2023/4/23 14:06
* @Des: UserInfoServiceImpl
*/
/**
* WebService涉及到的有这些 "四解三类 ", 即四个注解,三个类
* @WebMethod
* @WebService
* @WebResult
* @WebParam
* SpringBus
* Endpoint
* EndpointImpl
*
* 一般我们都会写一个接口,然后再写一个实现接口的实现类,但是这不是强制性的
* @WebService 注解表明是一个webservice服务。
* name:对外发布的服务名, 对应于<wsdl:portType name="ServerServiceDemo"></wsdl:portType>
* targetNamespace:命名空间,一般是接口的包名倒序, 实现类与接口类的这个配置一定要一致这种错误
* Exception in thread "main" org.apache.cxf.common.i18n.UncheckedException: No operation was found with the name xxxx
* 对应于targetNamespace="http://server.webservice.example.com"
* endpointInterface:服务接口全路径(如果是没有接口,直接写实现类的,该属性不用配置), 指定做SEI(Service EndPoint Interface)服务端点接口
* serviceName:对应于<wsdl:service name="ServerServiceDemoImplService"></wsdl:service>
* portName:对应于<wsdl:port binding="tns:ServerServiceDemoImplServiceSoapBinding" name="ServerServiceDemoPort"></wsdl:port>
*
* @WebMethod 表示暴露的服务方法, 这里有接口ServerServiceDemo存在,在接口方法已加上@WebMethod, 所以在实现类中不用再加上,否则就要加上
* operationName: 接口的方法名
* action: 没发现又什么用处
* exclude: 默认是false, 用于阻止将某一继承方法公开为web服务
*
* @WebResult 表示方法的返回值
* name:返回值的名称
* partName:
* targetNamespace:
* header: 默认是false, 是否将参数放到头信息中,用于保护参数,默认在body中
*
* @WebParam
* name:接口的参数
* partName:
* targetNamespace:
* header: 默认是false, 是否将参数放到头信息中,用于保护参数,默认在body中
* model:WebParam.Mode.IN/OUT/INOUT
*/
@Service
@WebService(serviceName = "userInfoService", targetNamespace = "http://server.webservice.gtp.sinotrans.com", endpointInterface = "com.sinotrans.gtp.webservice.UserInfoService")
@Slf4j
public class UserInfoServiceImpl implements UserInfoService {
@Override
public void saveUserInfo(UserInfo userInfo) {
System.out.println("保存用户信息成功" + userInfo.toString());
}
@Override
public UserInfo getUserInfoById(Long id) {
UserInfo zhangsan = UserInfo.builder().id(1L).username("zhangsan").password("123456").build();
log.info(JsonUtil.toJson(zhangsan));
return zhangsan;
}
}
2.5. 配置类
import com.sinotrans.gtp.interceptor.WebServiceAuthInterceptor;
import com.sinotrans.gtp.webservice.AgeInfoService;
import com.sinotrans.gtp.webservice.UserInfoService;
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.beans.factory.annotation.Autowired;
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:wangdi
* @Date:2023/4/23 14:07
* @Des: CXFConfig
*/
@Configuration
public class WebServiceConfig {
@Autowired
private UserInfoService userInfoService;
@Autowired
private AgeInfoService ageInfoService;
// @Autowired
// private WebServiceAuthInterceptor interceptor;
/**
* Apache CXF 核心架构是以BUS为核心,整合其他组件。
* Bus是CXF的主干, 为共享资源提供一个可配置的场所,作用类似于Spring的ApplicationContext,这些共享资源包括
* WSDl管理器、绑定工厂等。通过对BUS进行扩展,可以方便地容纳自己的资源,或者替换现有的资源。默认Bus实现基于Spring架构,
* 通过依赖注入,在运行时将组件串联起来。BusFactory负责Bus的创建。默认的BusFactory是SpringBusFactory,对应于默认
* 的Bus实现。在构造过程中,SpringBusFactory会搜索META-INF/cxf(包含在 CXF 的jar中)下的所有bean配置文件。
* 根据这些配置文件构建一个ApplicationContext。开发者也可以提供自己的配置文件来定制Bus。
*/
@Bean(name = Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
return new SpringBus();
}
/**
* 设置WebService访问父路径
* <p>
* 此方法作用是改变项目中服务名的前缀名,此处127.0.0.1或者localhost不能访问时,请使用ipconfig查看本机ip来访问
* 此方法被注释后, 即不改变前缀名(默认是services), wsdl访问地址为 http://127.0.0.1:8080/services/ws/api?wsdl
* 去掉注释后wsdl访问地址为:http://127.0.0.1:8080/webServices/ws/api?wsdl
* http://127.0.0.1:8080/soap/列出服务列表 或 http://127.0.0.1:8080/soap/ws/api?wsdl 查看实际的服务
* 新建Servlet记得需要在启动类添加注解:@ServletComponentScan
* 如果启动时出现错误:not loaded because DispatcherServlet Registration found non dispatcher servlet dispatcherServlet
* 可能是springboot与cfx版本不兼容。
* 同时在spring boot2.0.6之后的版本与xcf集成,不需要在定义以下方法,直接在application.properties配置文件中添加:
* cxf.path=/service(默认是services)
*/
@Bean
public ServletRegistrationBean getRegistrationBean() {
return new ServletRegistrationBean(new CXFServlet(), "/webServices/*");
}
@Bean
public Endpoint messageEndPoint() {
EndpointImpl endpoint = new EndpointImpl(springBus(), this.userInfoService);
endpoint.publish("/userInfoService");
// endpoint.getInInterceptors().add(this.interceptor);
return endpoint;
}
/*用于发布多个WebService*/
// @Bean
// public Endpoint messageEndPoint2() {
// EndpointImpl endpoint = new EndpointImpl(springBus(), this.ageInfoService);
// endpoint.publish("/userInfoService");
endpoint.getInInterceptors().add(this.interceptor);
// return endpoint;
// }
}
2.6. 拦截器类(如有需要)
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.springframework.stereotype.Component;
import org.w3c.dom.NodeList;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
/**
* @Author:wangdi
* @Date:2023/4/23 14:10
* @Des: WebServiceAuthInterceptor
*/
@Component
@Slf4j
public class WebServiceAuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
/**
* 用户名
*/
private static final String USER_NAME = "wangdi";
/**
* 密码
*/
private static final String USER_PASSWORD = "wangdi.com";
private static final String NAME_SPACE_URI = "http://server.webservice.gtp.sinotrans.com";
/**
* 创建拦截器
*/
private SAAJInInterceptor interceptor = new SAAJInInterceptor();
public WebServiceAuthInterceptor() {
super(Phase.PRE_PROTOCOL);
//添加拦截
super.getAfter().add(SAAJInInterceptor.class.getName());
}
@Override
public void handleMessage(SoapMessage message) throws Fault {
//获取指定消息
SOAPMessage soapMessage = message.getContent(SOAPMessage.class);
if (null == soapMessage) {
this.interceptor.handleMessage(message);
soapMessage = message.getContent(SOAPMessage.class);
}
//SOAP头信息
SOAPHeader header = null;
try {
header = soapMessage.getSOAPHeader();
} catch (SOAPException e) {
e.printStackTrace();
}
if (null == header) {
throw new Fault(new IllegalAccessException("没有Header信息,无法实现用户认证处理!"));
}
//SOAP是基于XML文件结构进行传输的,所以如果要想获取认证信息就必须进行相关的结构约定
NodeList usernameNodeList = header.getElementsByTagNameNS(NAME_SPACE_URI, "username");
NodeList passwordNodeList = header.getElementsByTagNameNS(NAME_SPACE_URI, "password");
if (usernameNodeList.getLength() < 1) {
throw new Fault(new IllegalAccessException("没有用户信息,无法实现用户认证处理!"));
}
if (passwordNodeList.getLength() < 1) {
throw new Fault(new IllegalAccessException("没有密码信息,无法实现用户认证处理!"));
}
String username = usernameNodeList.item(0).getTextContent().trim();
String password = passwordNodeList.item(0).getTextContent().trim();
if (USER_NAME.equals(username) && USER_PASSWORD.equals(password)) {
log.info("用户访问认证成功!");
} else {
SOAPException soapException = new SOAPException("用户认证失败!");
log.info("用户认证失败!");
throw new Fault(soapException);
}
}
}
3. 启动
http://localhost:8080/webServices/
点击链接可以查看到具体的接口信息
4. [客户端] 开发
4.1. 新建客户端拦截器类(如有需要)
对应2.4
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.headers.Header;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.namespace.QName;
import java.util.List;
/**
* @Author:wangdi
* @Date:2023/4/23 15:45
* @Des: ClientLoginInterceptor
*/
public class ClientLoginInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
private String username;
private String password;
private static final String NAME_SPACE_URI = "http://server.webservice.gtp.sinotrans.com";
public ClientLoginInterceptor(String username, String password) {
super(Phase.PREPARE_SEND);
this.username = username;
this.password = password;
}
@Override
public void handleMessage(SoapMessage soapMessage) throws Fault {
List<Header> headers = soapMessage.getHeaders();
Document document = DOMUtils.createDocument();
Element authority = document.createElementNS(NAME_SPACE_URI, "authority");
Element username = document.createElementNS(NAME_SPACE_URI, "username");
Element password = document.createElementNS(NAME_SPACE_URI, "password");
username.setTextContent(this.username);
password.setTextContent(this.password);
authority.appendChild(username);
authority.appendChild(password);
headers.add(0, new Header(new QName("authority"), authority));
}
}
4.2. 新建客户端调用接口
也可以在main方法中编写
调用之前 需要启动SpringBoot
import com.sinotrans.gtp.entity.UserInfo;
import com.sinotrans.gtp.interceptor.ClientLoginInterceptor;
import com.sinotrans.gtp.webservice.UserInfoService;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.stereotype.Component;
/**
* @Author:wangdi
* @Date:2023/4/23 15:51
* @Des: UserInfoApiClient
*/
@Component
public class UserInfoApiClient {
private static final String USERNAME = "wangdi";
private static final String PASSWORD = "wangdi.com";
private static final String ADDRESS = "http://localhost:8080/webServices/userInfoService?wsdl";
/**
* 使用代理方法
* @param userInfo
*/
public void saveUserInfoWithProxy(UserInfo userInfo) {
JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
jaxWsProxyFactoryBean.setAddress(ADDRESS);
jaxWsProxyFactoryBean.setServiceClass(UserInfoService.class);
jaxWsProxyFactoryBean.getOutInterceptors().add(
new ClientLoginInterceptor(USERNAME, PASSWORD)
);
UserInfoService userInfoService = (UserInfoService) jaxWsProxyFactoryBean.create();
userInfoService.saveUserInfo(userInfo);
}
/**
* 使用动态代理
* @param id
* @throws Exception
*/
public void getUserInfoByIdWithDynamic(Long id) throws Exception {
JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance();
Client client = clientFactory.createClient(ADDRESS);
client.getOutInterceptors().add(new ClientLoginInterceptor(USERNAME, PASSWORD));
Object[] userInfos = client.invoke("getUserInfoById", id);
String userInfo = userInfos[0].toString();
System.out.println(userInfo);
}
}
客户端使用动态代理访问时,参数中有bean对象时会提示类型转换错误异常
4.3. main方法中只显示INFO类日志
加入以下代码到类中
static {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
List<Logger> loggerList = loggerContext.getLoggerList();
loggerList.forEach(logger -> {
logger.setLevel(Level.INFO);
});
}
5. Postmen中调用
可结合浏览器插件 Wizdler
地址栏输入Web Service 接口地址,选择post方式,Headers中设置Content-Type为text/xml;charset=utf-8
。
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<getUserInfoById xmlns="http://server.webservice.gtp.sinotrans.com">
<id xmlns="">1</id>
</getUserInfoById>
</Body>
</Envelope>
6. 其他WebService调用方式
6.1. RestTemplate
maven依赖
<dependency>
<groupId>org.apache.cassandra</groupId>
<artifactId>cassandra-all</artifactId>
<version>0.8.1</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
配置类
/**
* @Author:wangdi
* @Date:2023/4/24 9:56
* @Des: RestTemplateConfig
*/
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
// 超时
factory.setConnectionRequestTimeout(5000);
factory.setConnectTimeout(5000);
factory.setReadTimeout(5000);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(createIgnoreVerifySSL(),
// 指定TLS版本
null,
// 指定算法
null,
// 取消域名验证
new HostnameVerifier() {
@Override
public boolean verify(String string, SSLSession ssls) {
return true;
}
});
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
factory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);
// 解决中文乱码问题
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
public static HttpHeaders getWSHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_XML);
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.TEXT_XML);
headers.setAccept(acceptableMediaTypes);
return headers;
}
/**
* 跳过证书效验的sslcontext
*
* @return
* @throws Exception
*/
private SSLContext createIgnoreVerifySSL() {
try {
SSLContext sc = SSLContext.getInstance("TLS");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[]{trustManager}, null);
return sc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
调用测试
/**
* @Author:wangdi
* @Date:2023/4/24 9:58
* @Des: RestTest
*/
@Slf4j
public class RestTest extends SinogtpApplicationTests {
// 使用之前注入
@Autowired
private RestTemplate rt;
@Test
public void test() {
String xml = "xml报文";
String url = "调用地址";
ResponseEntity<String> response = null;
try {
log.info("\n\n\n下发:" + xml + "\n\n\n");
HttpEntity<Object> requestEntity = new HttpEntity<Object>(xml, RestTemplateConfig.getWSHeaders());
response = rt.exchange(url, HttpMethod.POST, requestEntity, String.class);
} catch (RestClientResponseException e) {
log.error("\n\n\nError: " + e.getResponseBodyAsString() + "\n\n\n");
throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "出错");
}
log.info(response.getBody());
System.out.println();
}
}
6.2. 直接AXIS调用远程的web service
未验证
参考: https://cloud.tencent.com/developer/article/1148263
https://blog.csdn.net/LLLLLer/article/details/128103465
maven依赖
maven依赖(已验证)
<dependency>
<groupId>org.apache.axis</groupId>
<artifactId>axis</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-discovery</groupId>
<artifactId>commons-discovery</artifactId>
<version>0.2</version>
</dependency>
<dependency>
<groupId>org.apache.axis</groupId>
<artifactId>axis-jaxrpc</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.apache.axis</groupId>
<artifactId>axis-saaj</artifactId>
<version>1.4</version>
</dependency>
测试
maven依赖(未验证)
// //服务地址
// String url = "http://localhost:8080/webServices/userInfoService?wsdl";
// try {
// Service service = new Service();
// Call call = (Call) service.createCall();
// call.setTargetEndpointAddress(url);
// //第一个参数命名空间,第二个参数方法名
QName qname = new QName("命名空间", "接口名");
// QName qname = new QName("http://server.webservice.gtp.sinotrans.com", "getUserInfoById");
// call.setOperationName(qname);
call.addParameter("参数名", Constants.XSD_STRING, javax.xml.rpc.ParameterMode.IN);
// call.addParameter("id", Constants.XSD_LONG, javax.xml.rpc.ParameterMode.IN);
// //设置返回类型
// call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);
// //调用方法并传递参数 比如这样{\"NAME\":\"\"}
String resultStr = (String) call.invoke(new Object[]{"参数值"});
// String resultStr = (String) call.invoke(new Object[]{(long)1});
// System.out.println("服务调用结果:" + resultStr);
// } catch (Exception e) {
// e.printStackTrace();
// }