response.encoding = ‘utf-8‘不生效?

response.encoding = 'utf-8' 不起作用的原因是,虽然 UTF-8 是最常用的字符编码格式,但在处理带有 \u 形式的 Unicode 转义字符时,UTF-8 编码不会自动将它们转换为可读的中文。utf-8 适合解析直接的二进制内容,而 \uXXXX 形式的 Unicode 字符需要使用 unicode_escape 来正确解析。

区别说明

  • utf-8 编码:适合解析包含中文字符的字节流,但不会自动解析带有 \u 转义格式的 Unicode 字符。
  • unicode_escape 编码:能够将字符串中的 \uXXXX 格式自动解码为对应的中文字符。

示例对比

假设你的数据内容类似:

'{"retCode":200,"retDesc":"\\u89e3\\u6790\\u6210\\u529f"}'

此时,response.encoding = 'utf-8' 输出的 response.text 仍然会显示 \u89e3\u6790\u6210\u529f。而使用 unicode_escape 则能正确显示为 解析成功

正确的方式

如果返回的数据中含有 \uXXXX 形式的 Unicode 转义字符,推荐如下做法:

import requests
import json

url = "http://example.com/api"  # 替换为实际接口
response = requests.get(url)

# 使用 'utf-8' 编码读取初始文本,防止乱码
response.encoding = 'utf-8'
raw_text = response.text

# 将文本进行二次处理,解析 Unicode 转义字符
parsed_data = json.loads(raw_text)
parsed_data["retDesc"] = parsed_data["retDesc"].encode().decode('unicode_escape')

print(parsed_data)

这样做可以确保文本内容在经过 UTF-8 编码后,再正确解析 Unicode 转义字符。

这是demo.java文件内容:import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import javax.servlet.annotation.WebServlet; import java.io.IOException; @WebServlet("/demo") public class demo extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.print("你好"); response.getWriter().write("你好"); } }web.xml的内容:<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> </web-app>这是pom.xml的文件内容:<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>javaweb</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <maven.compiler.source>22</maven.compiler.source> <maven.compiler.target>22</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <!--Servlet依赖坐标--> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies> </project>你看看是不是 配置出错导致的404?
最新发布
05-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不做超级小白

大侠,喜欢的话可以打赏一下哦~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值