java—使用在httpclient 4.3.x中不起作用的非ascii凭据

4xy9mtcn  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(417)

我查阅了httpclient4.3.3api,了解如何指定要用于头的字符集,以便包含用户名/密码的授权头可以使用特定的字符集,如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,但我似乎不知道如何/在何处使用它指定字符集。

yquaqz18

yquaqz181#

自定义字符集编码适用于某些身份验证方案(如basic和digest),而不适用于其他方案。全局自定义auth字符集参数是个坏主意
必须使用自定义身份验证方案工厂在每个方案的基础上配置凭据字符集

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();

相关问题