StringEntity格式编码问题

    最近使用Apache的httpclient发起httpPost请求,后端一直提示编码格式错误。代码和环境都是在UTF-8写处理的,后端接受的编码也是UTF-8,但是后端依然报错。在跟踪代码的时候,发现主要是客户端StringEntity的处理问题。StringEntity设置编码格式主要有以下两种方式
//第一种方式:后端无法解码
StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params));
stringEntity.setContentType("UTF-8");

//第二种方式:请求成功
StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params), "UTF-8");
 在跟踪源码的时候,发现StringEntity的处理逻辑如下:
public StringEntity(String string) throws UnsupportedEncodingException {
        this(string, ContentType.DEFAULT_TEXT);
}

public StringEntity(String string, ContentType contentType) throws UnsupportedCharsetException {
        Args.notNull(string, "Source string");
        Charset charset = contentType != null ? contentType.getCharset() : null;
        if (charset == null) {
            charset = HTTP.DEF_CONTENT_CHARSET;
        }

        this.content = string.getBytes(charset);
        if (contentType != null) {
            this.setContentType(contentType.toString());
        }

 }

   当不传入ContentType时,会使用默认值,而该处的默认编码格式是:ISO_5598_1。所以后端才会提示异常。

    总结:使用httpclient时,尽量使用第二种方式来初始化StringEntity,避免因为编码格式导致异常。

  • 8
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值