Requests 是一个 Python 的 HTTP 客户端库,
需要安装 pip install requests,
使用时需要导入 import requests。
1、发送请求
1.1 无参数的get请求
res = requests.get(url='https://losthost/events')
1.2 带参数的get请求,通过params传参
res = requests.get(url='http://losthost', params={'key':'value'})
1.3 Post请求-form表单
正文格式urlencouded, 通过data传参
res=requests.post(url='http://losthost', data={'key':'value'},
headers={'Content-Type':'application/x-www-form-urlencoded'})
1.4 Post请求-XML
正文格式xml, 通过data传参
res=requests.post(url='http://losthost',
data='xml数据',
headers={'Content-Type': 'text/xml'})
1.5 Post请求-JSON
正文大部分是data= {}格式
res = requests.post(url="http://losthost",
json={"key": "value"}) # 明确知道正文是json格式
res = requests.post(url="http://losthost",
data='{"theCityCode": "1001"}')
import json
>>> url = 'https://losthost'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, data=json.dumps(payload))
1.6 Post请求-multipart/form-data
上传接口upload file
res = requests.post(url="http://losthost/api/uploadFile/",
files={"myfile": open("d://1.txt", 'rb')})
res = requests.post(url="http://losthost/api/uploadFile/",
files={"name":"zhangsan", "touxiang": "d://1.jpg", "shenfenzheng":"2.jpg"})
2、响应内容
响应状态码 :res.status_code
响应头 :res.headers
文本流信息 :res.text
Cookies : res.cookies
响应时间(毫秒) :round(r.elapsed.total_seconds()*1000)
获取响应头中Location : res.history[0].headers.get('Location')
响应头信息 : res.headers.get("Content-Type")
取请求信息 : res.request.headers["Cookie"]
#获取cookie 1. 先取响应头,再从响应头里拿 set-cookie
res = requests.post(url="http://losthost/api/login/",
data={"username": "admin", "p": "xxxxx"},
allow_redirects=False)
print(res.headers.get("set-cookie"))
# res.json() --- 将接口的响应json字符串 转换成python中的字典格式
# 反序列化 json(有序)-- 字典(无序)
3、请求其他参数
重定向 : allow_redirects=False
请求历史 :history
超时 : timeout
cookie超时 :可以传json形式参数,也可以把 Cookie Jar 传到 Requests
4、高级应用-session 发起请求(全局session)
session = requests.Session()
session.post(url="http://losthost/api/login/",
data={"username": "admin", "p": "xxxxx"})
res = session.post(url="http://losthost/api/get_salesMonthly/",
json={"city": "310000", "month": "3"})