上一篇博客简单描述了怎么发送get请求,那么这一篇简要描述怎么发送post请求,以及入参形式、封装等
1、发送post请求
以聚合数据中"历史上的今天"接口为例
import requests
url = 'http://api.juheapi.com/japi/toh'
data = {
"key":"7486da7f50cd55e6774fb3311b526d**",
"v":'1.0',
"month":12,
"day":15
}
# 使用post发送请求时,大部分入参是以json形式传参,那么使用json=data即可
res = requests.post(url=url,data=data)
print(res.json())
2、入参形式
2.1 parmas 传递查询字符串参数(get请求)
上一篇博客中有提到发送get请求,使用parmas传递参数
2.2 json类型的参数:参数类型为:Content-Type:application/json
res=requests.post(url=url,json=data)
2.3 表单类型的参数:Content-Type:“application/x-www-from-urlencoded”
response=requests.post(url=url,data=data)
2.4 from-data参数(用于上传文件):content-type:multipart/form-data
# files为字典类型数据,上传的文件为键值对的形式,参数名作为键
# 参数值是一个元组,内容为以下格式(文件名,打开的文件流,文件类型)
# file_data = {"参数名":("文件名",open("1215post请求.py","rb"),"text/py")}
# 注意:除上传的文件,接口的其他参数不能放在files中
file_data = {
"test":("1215post请求.py",open("1215post请求.py","rb"),"text/py")
}
response = requests.post(url=url,files=file_data)
3、请求头
发送请求很多时候都需要添加一个User-Agent的请求头,因为很多接口都做了反爬虫操作,确认请求是用户发送的,不是代码发送的,详细解释可以百度。
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36"
}
# 发送请求时也一并加上请求头
response = requests.get(url=url,headers=headers)
print(response.headers)
4、封装
使用cookie + session鉴权的请求类进行封装(后续博客会介绍cookie、session作用以及区别)
import requests
class SendRequest():
def __init__(self):
# 创建sesion对象,后面使用创建的对象发送请求,不需要使用request.get/post发送请求了
self.session = requests.session()
def sendrequest(self, url, method, headers=None, params=None, data=None, json=None, files=None):
# 调用send方法时,防止请求类型传入大写报错,统一转换为小写
method = method.lower()
if method == "get":
response = self.session.get(url=url, params=params, headers=headers)
elif method == "post":
response = self.session.post(url=url, json=json, data=data, files=files, headers=headers)
return response
# 调用封装类发送聚合数据中"历史上的今天"接口
if __name__ == '__main__':
Send = SendRequest()
url = 'http://api.juheapi.com/japi/toh'
data = {
"key":"7486da7f50cd55e6774fb3311b526d**",
"v":'1.0',
"month":12,
"day":15
}
A = Send.send(url=url,method='post',data=data)
print(A.json())
输出结果