有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java CXF RESTful客户端如何在没有Spring的情况下进行基本http身份验证?

我熟悉使用Jersey创建RESTful Web服务服务器和客户端,但由于class loading issues,我正在尝试将Jersey客户端转换为CXF。我相信我想使用以HTTP为中心的客户端,但我们不使用Spring。我们需要使用基本的HTTP身份验证。{a2}有以下示例:

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) 个答案

  1. # 1 楼答案

    这个答案来自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
    }