【问题标题】:Use of non-ascii credentials not working in httpclient 4.3.x使用非 ascii 凭据在 httpclient 4.3.x 中不起作用
【发布时间】:2015-01-16 01:35:02
【问题描述】:

我查阅了 httpclient 4.3.3 API,了解如何指定用于标头的字符集,以便包含用户名/密码的授权标头可以使用特定的字符集,例如 UTF-8 或 iso-8859-1。用于此的已弃用的 3.x API 是

httpMethodInstance.getParams().setHttpElementCharset("iso-8859-1");

我在 ConnectionConfig 中找到了 4.3.3 中的等效 API。以下是我尝试使用的代码

HttpClientBuilder builder = HttpClientBuilder.create();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(username, password));

builder.setDefaultCredentialsProvider(credentialsProvider);

ConnectionConfig connectionConfig = ConnectionConfig.custom()
        .setCharset(Charset.forName("iso-8859-1")).build();
BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(
        registryBuilder.build());
connManager.setConnectionConfig(connectionConfig);
builder.setConnectionManager(connManager);



HttpHost target = new HttpHost(host, port, scheme);
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

CloseableHttpClient httpclient = builder.build();
CloseableHttpResponse response = httpclient.execute(target, request, localContext);

但在授权标头中发送的凭据的 base64 编码值表明凭据未使用指定的字符集“iso-8859-1”进行编码。 ConnectionConfig.setCharset() 是用于设置 http 标头字符集的正确方法吗?如果不是,4.3.x 中已弃用的 setHttpElementCharset() 的正确等效项是什么?

Apache 邮件存档 http://mail-archives.apache.org/mod_mbox/hc-dev/201407.mbox/%3CJIRA.12727350.1405435834469.45355.1405437005945@arcas%3E 表示这并不容易得到支持,并建议使用 BasicSchemeFactory 但我似乎无法弄清楚如何/在哪里使用它来指定字符集。

【问题讨论】:

    标签: java character-encoding apache-httpclient-4.x


    【解决方案1】:

    自定义字符集编码适用于某些身份验证方案(如 Basic 和 Digest),不适用于其他身份验证方案。全局自定义身份验证字符集参数是个坏主意

    必须使用自定义身份验证方案工厂在每个方案的基础上配置凭据字符集

    Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.BASIC, new BasicSchemeFactory(Consts.UTF_8))
                .register(AuthSchemes.DIGEST, new DigestSchemeFactory(Consts.UTF_8))
                .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
                .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory())
                .build();
    CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultAuthSchemeRegistry(authSchemeRegistry)
            .build();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多