繁体   English   中英

java Apache Cxf HTTP身份验证

[英]java Apache Cxf HTTP authentication

我有WSDL 我需要进行HTTP基本(抢先)身份验证。 该怎么办?

我试过了 :

Authenticator myAuth = new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("user", "pass".toCharArray());
    }
};
Authenticator.setDefault(myAuth);

但它不起作用:引起:

java.io.IOException:服务器返回HTTP响应代码:401为URL ..

PS我使用Apache CXF 2.6.2和JBoss 5.0.1

您为身份验证指定的内容是不够的。 你应该做这样的事情:

private YourService proxy;

public YourServiceWrapper() {
    try {
        final String username = "username";
        final String password = "password";
        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                        username,
                        password.toCharArray());
            }
        });
        URL url = new URL("http://yourserviceurl/YourService?WSDL");
        QName qname = new QName("http://targetnamespace/of/your/wsdl", "YourServiceNameInWsdl");
        Service service = Service.create(url, qname);
        proxy = service.getPort(YourService.class);
        Map<String, Object> requestContext = ((BindingProvider) proxy).getRequestContext();
        requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url.toString());
        requestContext.put(BindingProvider.USERNAME_PROPERTY, username);
        requestContext.put(BindingProvider.PASSWORD_PROPERTY, password);
        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
    } catch (Exception e) {
        LOGGER.error("Error occurred in web service client initialization", e);
    }
}

属性:

  1. YourService - 您生成的Web服务客户端界面。
  2. YourServiceWrapper() - 初始化服务的包装类构造函数。
  3. url - 具有?WSDL扩展名的Web服务的URL。
  4. qname - 第一个构造函数参数:来自WSDL文件的目标命名空间。 第二:来自WSDL的服务名称。

然后,您将能够像这样调用您的Web服务方法:

proxy.whatEverMethod();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM