CXF RESTful Client - 如何在没有Spring的情况下进行基本的http身份验证?

时间:2011-10-24 19:18:16

标签: java rest client cxf http-authentication

我熟悉使用Jersey创建RESTful webservice服务器和客户端,但由于class loading issues,我试图将Jersey客户端转换为CXF。我相信我想使用以HTTP为中心的客户端,但我们不使用Spring。我们需要使用基本的HTTP身份验证。 user guide有这个例子:

WebClient client = WebClient.create("http:books", "username", "password", "classpath:/config/https.xml");

第一个参数不是URI字符串。它是Spring使用的格式吗?此方法只能用于使用Spring创建WebClient吗?

显示身份验证的另一种方法是添加标题字符串:

String authorizationHeader = "Basic " + org.apache.cxf.common.util.Base64Utility.encode("user:password".getBytes());
webClient.header("Authorization", authorizationHeader);

我猜测"user:password"应该用实际值代替,但我们希望得到确认。

1 个答案:

答案 0 :(得分:9)

这个答案来自CXF用户邮件列表。

上面提到的第一个例子中有一个拼写错误。它已更新为:

WebClient client = WebClient.create("http://books", "username", "password", "classpath:/config/https.xml");

如果没有使用Spring配置文件(因此Spring),则第四个参数可以为null。

所以,这对我有用:

private WebClient webClient;

public RESTfulClient(String url, String username, String password)
        throws IllegalArgumentException
{
    this.username = username;
    this.password = password;
    this.serviceURL = url;

    if (username == null || password == null || serviceURL == null)
    {
        String msg = "username, password and serviceURL MUST be defined.";
        log.error(msg);
        throw new IllegalArgumentException(msg);
    }

    webClient = WebClient.create(this.serviceURL,
            this.username,
            this.password,
            null); // Spring config file - we don't use this
}
相关问题