如何使用Python的requests.post实现Postman的POST数据提交
用Python requests实现Postman同款POST提交
先装依赖
没装requests库的话先执行这个命令:
pip install requests
直接上代码
从你提供的Postman配置来看,是提交x-www-form-urlencoded格式的表单,目标地址为http://localhost:8080/login,携带username和password两个参数,对应Python代码如下:
import requests # 替换成你实际的接口地址 url = "http://localhost:8080/login" # 填入你Postman里的真实参数值 form_data = { "username": "你的用户名", "password": "你的密码" } # 发送POST请求 res = requests.post(url, data=form_data) # 查看响应结果 print("响应状态码:", res.status_code) print("响应内容:", res.text)
额外说明
- 用
data参数提交时,requests会自动设置Content-Type: application/x-www-form-urlencoded,和你Postman里的配置完全匹配,无需手动添加请求头。 - 如果需要维持会话(比如登录后继续请求其他关联接口),可以改用
requests.Session(),把后续请求都挂载在会话对象上即可。
内容的提问来源于stack exchange,提问作者AkifObaidi
相关产品推荐
相关产品推荐

