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)

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐