下面分别是get,post,入参json,添加cookie,添加header,上传/下载文件 的接口请求举例:
import requests #导入模块
#1.发get请求
url = 'http://api.xx**.cn/api/xx/stu_info'
data = {'stu_name':'xx'} #请求数据
req = requests.get(url,params=data) #发get请求
print(req.json()) #返回字典类型
print(req.text()) #返回string,json串
#2.发post请求
url = 'http://api.xx**.cn/api/xx/login'
data = {'username':'lyl','passwd':'23456'} #请求数据
req = requests.post(url,data) #发post请求
print(req.json()) #返回json串
#3.入参是json类型的
import random
# phone=random.randint(10000000000,99999999999)
url='http://api.xx**.cn/api/xx/add_stu'
data = {
"name":"小1",
"grade":"天蝎座",
"phone":phone,
"sex":"男",
"age":28,
"addr":"河南省济源市北海大道32号"
}
req = requests.post(url,json=data) #请求数据
print(req.json())
#4、添加cookie
url = 'http://api.xx**.cn/api/xxx/gold_add'
data = {'stu_id':468,'gold':10000}
djl = {'fancy':'337ca4cc825302b3a8791ac7f9dc4bc6'}
req = requests.post(url,data,cookies=djl)
print(req.json())
#5.添加header
url = 'http://api.xx**.cn/api/xxx/all_stu'
header = {
'Referer':'http://api.xx**.cn/'
}
req = requests.get(url,headers=header)
print(req.json())
#6、上传文件
url= 'http://api.xx**.cn/api/file/file_upload'
data = {
'file':open(r'C:UsersxxddengDesktop图6bd9026dt935575932465&690.jpg','rb')
}
req= requests.post(url,files=data)
print(req.json())
#7、下载文件
url = 'http://up.mcyt.net/?down/46779.mp3'
req = requests.get(url)
fw = open('aaa.mp3','wb')
fw.write(req.content)