Java 如何使用 CXF 框架使用受 HTTP 基本身份验证保护的 Web 服务?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/705728/
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
How do I consume a web service protected with HTTP basic authentication using the CXF framework?
提问by ScArcher2
I tried to get it to work using the CXF User Guide, but I've had no luck.
我尝试使用CXF 用户指南让它工作,但我没有运气。
I'm trying to call the web service using java code.
我正在尝试使用 Java 代码调用 Web 服务。
采纳答案by Daniel Kulp
This is covered by the JAX-WS Specification. Basically, set the username/password as properties on the request context:
JAX-WS 规范涵盖了这一点。基本上,将用户名/密码设置为请求上下文中的属性:
((BindingProvider)proxy).getRequestContext().put(
BindingProvider.USERNAME_PROPERTY, "joe");
((BindingProvider)proxy).getRequestContext().put(
BindingProvider.PASSWORD_PROPERTY, "pswd");
The runtime puts them into the HTTP header.
运行时将它们放入 HTTP 标头中。
回答by Mohammad Dashti
There is a much better way:
有一个更好的方法:
when generating Java from WSDL, add option "-exsh true" :
从 WSDL 生成 Java 时,添加选项“-exsh true”:
wsdl2java -exsh true -p edu.sharif.ce http://wsdl.ir/WebServices/WebService.asmx?WSDL
wsdl2java -exsh true -p edu.sharif.ce http://wsdl.ir/WebServices/WebService.asmx?WSDL
and add UserCredential when using:
并在使用时添加 UserCredential:
UserCredentials user = new UserCredentials();
user.setUserid("user");
user.setPassword("pass");
ResearchWebService_Service service = new ResearchWebService_Service();
ResearchWebService port = service.getResearchWebService();
port.addNewProject(newProject, user);
回答by mikeltxo
You can provide your own Authenticator. That way it will work if the WDSL itself is protected by basic HTTP authentication.
您可以提供自己的身份验证器。这样,如果 WDSL 本身受到基本 HTTP 身份验证的保护,它将起作用。
@WebServiceRef(wsdlLocation = "https://laka/sito?wsdl")
static XxxService service;
public static void main(String[] args) {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "password".toCharArray());
}
});
service = new XxxService();
Xxx port = service.getXxxPort();
// invoke webservice and print response
XxxResponse resp = port.foo();
System.out.println(resp.toString());
}