【问题标题】:HttpClient Authenticator with Umlauts带有变音符号的 HttpClient Authenticator
【发布时间】:2021-09-01 11:37:01
【问题描述】:

如果密码包含(德语)变音符号,我如何配置 Java 11 HttpClient Authenticator 以正确编码密码?

这里是配置

    String username = "testuser";
    String password = "täst";
    Authenticator authenticator = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    };
    HttpClient build = HttpClient.newBuilder()//
            .sslContext(disabledSslVerificationContext())//
            .authenticator(authenticator).build();
    String url = server + "/ping";

    String body = "";

    HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)) //
            .header("Content-Type", "application/json") //
            .header("charset", "UTF-8") //
            .method("GET", BodyPublishers.ofString(body)).build();

我也尝试设置 .header("Content-Type", "text/html; charset=utf-8") 但这也没有用。

如果我出于调试目的将“密码”添加到标题中,我会在服务上看到我收到 t?st 而不是 täst。

如何指示服务器以正确的形式向服务器发送密码?

[编辑]

调试代码表明 jdk.internal.net.http.AuthenticationFilter#response 看不到我的字符集设置。此调用最终将 isUTF8 保持为 false,如果我在调试器中将其切换为 true,则密码将正确发送到服务器。

for (String aval : authvals) {
        HeaderParser parser = new HeaderParser(aval);
        String scheme = parser.findKey(0);
        if (scheme.equalsIgnoreCase("Basic")) {
            authval = aval;
            var charset = parser.findValue("charset");
            isUTF8 = (charset != null && charset.equalsIgnoreCase("UTF-8"));
            break;
        }
    }

我仍然没有找到指示 AuthenticationFilter 查看我的字符集设置的正确方法。有什么建议吗?

【问题讨论】:

  • 尝试\u00E4 而不是ä。这将检测 javac 编译器是否使用与编辑器相同的字符集编码。
  • \u00E4 也不起作用。

标签: java authentication httpclient java-11


【解决方案1】:

原来在 utf-8 中编码的能力是在 Java 11 之后的 Java 版本中才添加的,并且是由服务器响应头触发的。因此,我们必须配置我们的服务器以在其响应中返回某个元素。由于目前这对我们来说是不可能的(因为我们必须使用 Java 11),我们将密码编码为 ISO_8859_1。

    String encodedPW = new String(password.getBytes(), StandardCharsets.ISO_8859_1.toString());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 2019-12-08
    • 1970-01-01
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多