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¶m2=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
相关产品推荐
相关产品推荐

