You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache HttpClient 5.2如何禁用自动添加字符集功能?

禁用Apache HttpClient自动添加字符集到Content-Type头的方法

要让HttpClient严格发送Content-Type: application/x-www-form-urlencoded而不追加字符集,可通过以下两种方式实现:

方法一:使用StringEntity替代UrlEncodedFormEntity

直接构造URL编码后的表单参数字符串,创建StringEntity时指定不带字符集的Content-Type:

// 构造URL编码后的表单参数
String formContent = "param1=value1&param2=value2";
// 创建实体,明确指定Content-Type且不设置字符集
StringEntity entity = new StringEntity(formContent, ContentType.create("application/x-www-form-urlencoded", (Charset) null));

HttpPost request = new HttpPost("https://your-target-url.com");
request.setEntity(entity);

方法二:自定义UrlEncodedFormEntity的ContentType

若仍需使用UrlEncodedFormEntity,可在创建后覆盖默认的ContentType,移除字符集信息:

List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2", "value2"));

// 创建实体时传入null作为字符集,避免自动添加
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, (Charset) null);
// 强制设置不带字符集的Content-Type
entity.setContentType("application/x-www-form-urlencoded");

HttpPost request = new HttpPost("https://your-target-url.com");
request.setEntity(entity);

原理说明

Apache HttpClient的UrlEncodedFormEntity默认会根据传入的字符集(或默认UTF-8)自动追加; charset=xxx到Content-Type头。通过传入null作为字符集参数,或直接使用StringEntity并指定不含字符集的ContentType,即可绕过这一自动行为,确保请求头严格符合预期格式。

内容的提问来源于stack exchange,提问作者Hendrik Janßen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 22:35:59