记一次页面乱码问题的解决

 

问题描述

在通过httpclient调用其它应用时,返回结果出现乱码。

字符集问题

第一反应,服务端返回的字符集不对

检查了一下发送请求时的字符集配置,配置为

Content-Type:application/json;charset=UTF-8

经过在网上查资料,content-type是描述发送报文的字符集,而不是返回报文的字符集

返回报文的字符集通过accept来描述

Accept:application/json;charset=UTF-8

于是修改发送报文的header,将 accept改为 utf-8

但是问题并没有解决

总结:

Content-Type 用于描述request,而Accept用于描述reponse

Gzip

继续排查发现返回的报文header里面的accept encoding 为gzip

初步怀疑返回的报文被gzip压缩了

尝试对返回的报文进行解压缩

参考了网上其它文章内容

关键代码如下

    public static String getStringFromResponseUzip(final HttpResponse response) throws Exception {
      if (response == null) {
          return null;
      }
      String responseText = "";
      //InputStream in = response.getEntity().getContent();
      final InputStream in = response.getEntity().getContent();
      final Header[] headers = response.getHeaders("Content-Encoding");
      for(final Header h : headers){
          System.out.println(h.getValue());
          if(h.getValue().indexOf("gzip") > -1){
              //For GZip response
              try{
                  final GZIPInputStream gzin = new GZIPInputStream(in);
                  final InputStreamReader isr = new InputStreamReader(gzin,"UTF-8");
                  responseText = getStringFromStream(isr);
                  //responseText = URLDecoder.decode(responseText, "utf-8");
              }catch (final IOException exception){
                  exception.printStackTrace();
              }
              return responseText;
          }
      }
      responseText = EntityUtils.toString(response.getEntity(),"utf-8");
      return responseText;
  }

  public static String getStringFromStream(final InputStreamReader isr) throws Exception{
      final BufferedReader br = new BufferedReader(isr);
      final StringBuilder sb = new StringBuilder();
      String tmp;
      while((tmp = br.readLine())!=null){
          sb.append(tmp);
      }
      br.close();
      isr.close();
      return sb.toString();
  }
}

对报文进行解压之后,debug时已经看到返回的报文不再乱码

返回页面报错

虽然经过上面的解压,报文正常被解开,但是返回到前端页面依然报错。

最后检查返回部分内容,怀疑是返回的header里面依然配置了accept encoding,报文返回到前端以后,会对报文再进行一次解压缩。通过将header中的accept encoding去掉,返回页面也正常访问。

 

 

原文地址:https://www.cnblogs.com/liguangming/p/14921387.html