【Python】requests发送http json请求&utf-8编码

0 安装库+引用库

安装代码

pip install requests

引用库

import requests # http请求
import json # json数据格式

1 发送 http请求

# 需要发送http请求的url地址
url = "https://xxx.xxx.xxx" 
# 设置header
headers = {'content-type': "application/json"} 
# json数据
body = {"a":"a","b":"b"} 
# 发送请求
response = requests.post(url, data = json.dumps(body), headers = headers)
	

2 读取 http response

# 文本化返回值
response_msg = response.text

3 使用utf-8编码

注意事项:不仅需要在http header中添加charset赋值,还需要确认json数据转化为string时的编码格式(json.dumps 存在默认编码)

# 需要发送的 json 数据
body = {}
# json 数据格式转换不使用默认编码,再进行 utf-8编码转换
body = json.dumps(data, ensure_ascii=False).encode('utf8')
# 修改 header
headers = {"Content-Type" : "application/json;charset=utf-8"}
# 发送请求
response = requests.post(url, data = body, headers = headers)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值