java Apache Cxf HTTP 身份验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12891040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java Apache Cxf HTTP authentication
提问by Bera
I have WSDL
. I need to make HTTP
basic (preemptive) authentication.
What to do?
我有WSDL
。我需要进行HTTP
基本(抢占式)身份验证。该怎么办?
I tried :
我试过 :
Authenticator myAuth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "pass".toCharArray());
}
};
Authenticator.setDefault(myAuth);
But it does not work: Caused by:
但它不起作用: 引起:
java.io.IOException: Server returned HTTP response code: 401 for URL ..
java.io.IOException:服务器返回 HTTP 响应代码:URL 401 ..
P.S. I use Apache CXF 2.6.2 and JBoss 5.0.1
PS 我使用 Apache CXF 2.6.2 和 JBoss 5.0.1
回答by Paulius Matulionis
What you specified for your authentication is not enough. You should do something like this:
您为身份验证指定的内容是不够的。你应该做这样的事情:
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);
}
}
Properties:
特性:
- YourService - your generated web service client interface.
- YourServiceWrapper() - wrapper class constructor which initializes your service.
- url - URL to your web service with
?WSDL
extension. - qname - first constructor argument: target namespace from your
WSDL
file. Second: your service name fromWSDL
.
- YourService - 您生成的 Web 服务客户端界面。
- YourServiceWrapper() - 初始化服务的包装类构造函数。
- url - 带有
?WSDL
扩展名的 Web 服务的 URL 。 - qname - 第一个构造函数参数:
WSDL
文件中的目标命名空间。第二:您的服务名称来自WSDL
.
Then you will be able to call your web service methods like this:
然后你就可以像这样调用你的网络服务方法:
proxy.whatEverMethod();