使用 requests 进行接口调试
安装requests库
pip install requests
如何导包
import requests
get 无参请求
r = requests.get('http://www.baidu.com')
这样,就发送了一个五参的get请求,返回值r,是一个Response对像。还可以设置超时时间。
r = requests.get('http://www.baidu.com', timeout=1)
get 请求带上参数
url = 'http://localhost:9001/pytest/get'
params={'name':'yejing','age':32}
r = requests.get(url,params=params)
print(r.url)
输出的结果:
https://localhost:8080/requests/get?name=yejing&age=32
定制化请求头
url = 'https://www.baidu.com/s?wd=python'
headers = {
'Content-Type': 'text/html;charset=utf-8',
'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
}
r = requests.get(url,headers=headers)
r(Response)对象
r.url #打印输出该 URL
r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
r.status_code #返回连接状态,200正常。
r.text #默认以unicode形式返回网页内容,也就是网页源码的字符串。
r.content #以字节形式(二进制)返回。字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩。
r.json() #把网页中的json数据转成字典并将其返回。
r.encoding #获取当前的编码
r.encoding = 'ISO-8859-1' #指定编码,r.text返回的数据类型,写在r.text之前。
post 以form表单的方式请求:application/x-www-form-urlencoded
url = 'http://localhost:9001/pytest/postForm'
params = {'name': 'yejing','age': 32}
r = requests.post(url, data=params)
print(r.text)
post 以json的方式请求:application/json
url = 'http://localhost:9001/pytest/postJson'
params = {'name': 'yejing', 'age': 32}
r = requests.post(url,json=params)
#print(r.text)
print(r.headers.get('Content-Type'))
post 以json的方式请求2:application/json
url = 'http://localhost:9001/pytest/postJson'
params = {'name':'yejing','age':32,'date':'2020-04-04 6:18:35'}
headers = {'Content-Type':'application/json'}
r = requests.post(url,data=json.dumps(params),headers=headers)
print(r.content)
print(r.url)
print(r.headers)
print(r.headers['Content-Type'])
上传文件:multipart/form-data
url = 'http://localhost:9001/pytest/upload'
files = {'fileUpload': open('d:/a.txt', 'rb')}
r = requests.post(url,files=files)
print(r.content)
print(r.url)
print(r.headers)
print(r.headers['Content-Type'])