ws-client-demo
客户端调用远程服务
http://localhost:8280/services/HelloWorld?wsdl
spring + cfx 配置
maven
添加依赖包
org.apache.cxf
cxf-rt-frontend-jaxws
3.2.3
org.apache.cxf
cxf-rt-transports-http
3.2.3
wsdl2java
把 HelloWorld.wsdl 下载到 resources 当中
使用 maven 插件 cxf-codegen-plugin 生成代码
org.apache.cxf
cxf-codegen-plugin
3.2.2
generate-sources
generate-sources
${project.build.directory}/generated/cxf
${basedir}/src/main/resources/HelloWorld.wsdl
wsdl2java
maven compile 任务完成之后在target\generated\cxf\com\example\demo\ws
下会有很多文件
CurrentDate.java
CurrentDateResponse.java
HelloWorld.java
HelloWorldImplService.java
ObjectFactory.java
package-info.java
SayHi.java
SayHiResponse.java
调用 WebService
使用 spring
把 HelloWorld.java 复制到 srcmainjavacomexampledemows 目录下
同时 HelloWorld.java 里面 @XmlSeeAlso({ObjectFactory.class})这行代码删掉
package com.example.demo;
import com.example.demo.ws.service.HelloWorld;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.xml.datatype.XMLGregorianCalendar;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld client = (HelloWorld) context.getBean("helloClient");
String resp1 = client.sayHi("小明");
System.out.println(resp1);
XMLGregorianCalendar resp2 = client.currentDate();
System.out.println(resp2.toString());
}
}
不使用 spring
package com.example.demo;
import com.example.demo.ws.service.HelloWorld;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.MalformedURLException;
import java.net.URL;
public class WithoutSpring {
public static void main(String[] args) throws MalformedURLException {
URL wsdlURL = new URL("http://localhost:8280/services/HelloWorld?wsdl");
QName SERVICE_NAME = new QName("http://service.ws.demo.example.com/", "HelloWorldImplService");
Service service = Service.create(wsdlURL, SERVICE_NAME);
HelloWorld client = service.getPort(HelloWorld.class);
String result = client.sayHi("小红");
System.out.println(result);
}
}
可以直接运行的demo
GitHub https://github.com/openmartin...
其他配置
demo 中是比较简单的情况,但是实际的情况会更复杂,下面介绍一下常用的配置
SSL Certificate and Proxy
参考 https://cxf.apache.org/docs/c...
在 applicationContext.xml 可以为web service client 配置proxy 和 ssl cert,完全不用写代码。
ssl 证书有两种形式 pkcs12、jks, 指定路径有三种形式 url、file、resource
.*_EXPORT_.*
.*_EXPORT1024_.*
.*_WITH_DES_.*
.*_WITH_AES_.*
.*_WITH_NULL_.*
.*_DH_anon_.*
cxf-codegen-plugin
cxf 的 maven 插件可以指定参数来解决一下常见的问题(
参考 http://cxf.apache.org/docs/ws...
- 添加-autoNameResolution 解决wsdl中命名冲突
- 添加-p packagename 指定自动生成的包名
org.apache.cxf
cxf-codegen-plugin
3.2.2
generate-sources
generate-sources
${project.build.directory}/generated/cxf
${basedir}/src/main/resources/HelloWorld.wsdl
-autoNameResolution
-verbose
-p
com.example.demo.ws
wsdl2java