zoukankan      html  css  js  c++  java
  • Http响应乱码

    Http响应乱码

    方案1

    response.setHeader("Content-Type", "application/json");
    response.setCharacterEncoding("GBK");
    //Content-Type: application/json;charset=GBK
    //{code: "401", message: "未登录"}
    

    方案2

    response.setHeader("Content-Type", "application/json;charset=UTF-8");
    //{code: "401", message: "未登录"}
    //Content-Type: application/json;charset=UTF-8
    

    注意

    只设置Content-Type不带编码信息无效

    /*
    只设置Content-Type,没有带编码信息,String中的中文是UTF16编码的。tomcat以其默认的ISO-8859-1从String中获取字节。tomcat附加在Content-Type的编码是charset=ISO-8859-1,浏览器会以这个编码解码,但是得不到原始中文信息。
    */
    response.setHeader("Content-Type", "application/json");
    //{code: "401", message: "???"}
    //Content-Type: application/json;charset=ISO-8859-1
    

    只设置response.setCharacterEncoding("GBK"),知识tomcat以GBK编码从String对象中获取字节。但是此时没有Content-Type信息。也就是浏览器将会用默认的类型和编码解析响应。不一致也会出现乱码。

    //tomcat将字符串按GBK编码转为字节,但是浏览器收到字节后,按照默认编码解析将会乱码。
    response.setCharacterEncoding("GBK");
    //{"code":"401","message":"δ��¼"}
    
  • 相关阅读:
    #Leetcode# 21. Merge Two Sorted Lists
    #Leetcode# 118. Pascal's Triangle
    #LeetCode# 136. Single Number
    #Leetcode# 26. Remove Duplicates from Sorted Array
    #LeetCode# 167. Two Sum II
    #Leetcode# 58. Length of Last Word
    #LeetCode# 35. Search Insert Position
    POJ 2492 J-A Bug's Life
    #Leetcode# 27. Remove Element
    【前端】.easyUI.c#
  • 原文地址:https://www.cnblogs.com/mozq/p/11781397.html
Copyright © 2011-2022 走看看