ITEEDU

编程学习网


  • 首页

  • 标签

  • 分类

  • 归档

  • 关于

  • 旧站归档

  • 搜索

反向代理之http响应乱码分析

发表于 2017-03-09 更新于 2019-06-29 分类于 架构 , 反向代理

服务器响应测试代码

UTF-8字符集

response.setHeader("Content-Type", "application/json;charset=UTF-8");
response.getWriter().append("{\"resp_msg\":\"查询失败,查询条件不能为空\",\"resp_code\":\"9999\"}");

GBK字符集

response.setHeader("Content-Type", "application/json;charset=GBK");
response.getWriter().append("{\"resp_msg\":\"查询失败,查询条件不能为空\",\"resp_code\":\"9999\"}");

客户端响应解析代码

httpClient.executeMethod(postMethod);
String strData=new String(postMethod.getResponseBody());
String strData1=new String(postMethod.getResponseBody(),"UTF-8");
String strData2=new String(postMethod.getResponseBody(),"GBK");
String resultStr = postMethod.getResponseBodyAsString();

结果分析

postMethod.getResponseBody()会取到响应结果的byte[]数组,创建字符串时只有和response.setHeader中设置的字符集一致才不会乱码。

postMethod.getResponseBodyAsString()会自动取响应头Content-Type的编码做字符串解码,所以总是会得到正确的结果。

postMethod.getResponseBodyAsString()的内部代码

public String getResponseBodyAsString() throws IOException {
    byte[] rawdata = null;
    if (responseAvailable()) {
        rawdata = getResponseBody();
    }
    if (rawdata != null) {
        return EncodingUtil.getString(rawdata, getResponseCharSet());
    } else {
        return null;
    }
}
public String getResponseCharSet() {
    return getContentCharSet(getResponseHeader("Content-Type"));
}

过程分析

服务器会根据响应头Content-Type的编码对返回字符串做解码,类似str.getBytes(Content-Type响应头编码)。

客户端postMethod从流中取出的byte数组就是服务器解码的数组,要想得到正确的结果就要做new String(byte[],Content-Type响应头编码)生成字符串。

证心 微信支付

微信支付

# HttpClient
反向代理之http请求乱码分析
反向代理之HttpClient4基本使用
  • 文章目录
  • 站点概览

证心

367 日志
45 分类
78 标签
GitHub 微博
  1. 1. 服务器响应测试代码
  2. 2. 客户端响应解析代码
  3. 3. 结果分析
  4. 4. 过程分析
京ICP备16069454号 © 2020 证心