不想用postman,用python如何进行接口的调试

安装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'])
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值