zoukankan      html  css  js  c++  java
  • 记一次页面乱码问题的解决

     

    问题描述

    在通过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去掉,返回页面也正常访问。

     

     

  • 相关阅读:
    ES6/ES2015核心内容 import export
    JavaScript 标准参考教程(alpha) 阮一峰
    NPM 学习笔记整理
    (尚026)Vue_案例_动态初始化显示(尚025)
    (尚025)Vue_案例_静态组件
    (尚024)Vue_案例_交互删除
    (尚023)Vue_案例_交互添加
    (尚022)Vue案例_初始化显示(十分详细!!!)
    (尚021)Vue_eslint编码规范检查
    (尚020)Vue打包发布项目
  • 原文地址:https://www.cnblogs.com/liguangming/p/14921387.html
Copyright © 2011-2022 走看看