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

sdo*_*oca 6 java rest client cxf http-authentication

我熟悉使用Jersey创建RESTful webservice服务器和客户端,但由于类加载问题,我试图将Jersey客户端转换为CXF.我相信我想使用以HTTP为中心的客户端,但我们不使用Spring.我们需要使用基本的HTTP身份验证.的用户指南具有本实施例中:

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

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

执行身份验证的另一种方法是添加标头字符串:

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

我猜这"user:password"应该用真实的价值观代替,但我会很感激确认.

sdo*_*oca 10

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

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

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

如果没有使用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
}
Run Code Online (Sandbox Code Playgroud)