CXF调用webservice 客户端 带soap header认证

今天调用webservice接口需要用户密码认证,所以采用CXF框架,调用如下

CXF wsdl2java 生成java代码供客户端使用

首先下载apache-cxf-2.6.2在环境变量中配置CXF_HOME 值为E:\gavin\cxf\apache-cxf-3.0.0,在PATH中加入%CXF_HOME%\bin

在cmd窗口执行 

wsdl2java -encoding utf-8 -d E: http://xxxxxxxxxx/webServices/WebService?wsdl

生成的代码粘贴到项目中

然后使用CXF调用webservice

    public static void main(String[] args) {
        //获取服务接口
        OnlineUserService_Service service_service = new OnlineUserService_Service();
        OnlineUserService onlineUserService = service_service.getOnlineUserServiceImplPort();
        //配置验证信息
        Client client = ClientProxy.getClient(onlineUserService);
        Map outProps = new HashMap();
        outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
        outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
        //用户名
        outProps.put(WSHandlerConstants.USER, "admin");
        outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientPwdCallback.class.getName());
        client.getOutInterceptors().add(new WSS4JOutInterceptor(outProps));
        //调用服务
        StringBuilder sb = new StringBuilder();
        sb.append("");
        sb.append("xxxx");
        sb.append("");
        String s = onlineUserService.queryOnlineUsers(sb.toString());
        System.out.println(s);

    }

public class ClientPwdCallback implements CallbackHandler {

    @Override
    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
        //用户名
        String ident = "admin";
        //密码
        String passwd = "password";
        for (int i = 0; i < callbacks.length; i++) {
            WSPasswordCallback pc = (WSPasswordCallback)callbacks[i];
            pc.setPassword(passwd);
            pc.setIdentifier(ident);
        }
    }
}


使用jar包



你可能感兴趣的:(后端)