https://blog.csdn.net/showgood119/article/details/78856038
cxf作为web service客户端,有以下几种方式,分别说明在方式下怎样添加header权限认证
假设服务端已经设置了权限认证,并且头部信息为
-
<soapenv:Header>
-
<auth>
-
<name>admin</name>
-
<password>123456</password>
-
</auth>
-
</soapenv:Header>
方式一
1. 先添加统一的拦截器
-
public class ClientAuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
-
-
private static final String NAME = "admin";
-
-
private static final String PASSWORD = "123456";
-
-
public ClientAuthInterceptor() {
-
//准备发送阶段
-
super(Phase.PREPARE_SEND);
-
}
-
-
-
public void handleMessage(SoapMessage message) throws Fault {
-
List<Header> headers = message.getHeaders();
-
-
Document doc = DOMUtils.createDocument();
-
-
Element auth = doc.createElement("auth");
-
-
Element name = doc.createElement("name");
-
name.setTextContent(NAME);
-
-
Element password = doc.createElement("password");
-
password.setTextContent(PASSWORD);
-
-
auth.appendChild(name);
-
auth.appendChild(password);
-
-
headers.add(new Header(new QName(""), auth));
-
}
-
}
2. 编写客户端
-
public static void main(String args[]) {
-
JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance();
-
Client client = clientFactory.createClient("http://localhost:8080/admin/cxfService?wsdl");
-
try {
-
client.getOutInterceptors().add(new ClientAuthInterceptor());
-
Object[] result = client.invoke("sayHello", "KEVIN");
-
System.out.println(result[0]);
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
}
方式二
1. 先添加客户端的拦截器,跟方式一中的相同
2. 使用cxf提供的代码生成工具 wsdl2java 生成代码,wsdl2java的使用方式,请谷歌
wsdl2java -p com -d ../src -client -encoding utf-8 http://localhost:8080/admin/cxfService?wsdl
3.编写客户端
-
public static void main(String args[]) {
-
HelloWorldImplService ss = new HelloWorldImplService();//自动生成的类
-
HelloWorld port = ss.getHelloWorldImplPort();//自动生成的类
-
Client client= ClientProxy.getClient(port);
-
client.getOutInterceptors().add(new ClientAuthInterceptor());
-
System.out.println(port.sayHello("hello,world"));
-
}