【发布时间】: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