CXF客户端添加header权限认证

来源:互联网 发布:淘宝运费险多少钱 编辑:程序博客网 时间:2024/05/29 08:03

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);    }    @Override    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"));    }







阅读全文
0 0
原创粉丝点击