栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python的三种post请求

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python的三种post请求

#!/user/bin/env python

# -*-coding: utf-8 -*-i

mport requests

import json

#rep=requests.request("get",url="https://postman-echo.com/get?fool=barl&foo2=bar2")

par={"fool":"barl","foo2":"bar2"}

rep=requests.get(url="https://postman-echo.com/get",params=par)
print(rep.content)

rep1=requests.get("https://postman-echo.com/get?fool=barl&foo2=bar2")
print(rep1.content)

data={"fool":"barl","foo2":"bar2"}
rep4=requests.post("https://postman-echo.com/post",data=data)
print(rep4.text)

rep2=requests.request("post",url="https://postman-echo.com/post?fool=barl&foo2=bar2",data="this is data")
print(rep2.content)
print(type(rep2.content))
rep3=requests.post("https://postman-echo.com/post?fool=barl&foo2=bar2")


#取响应数据中值的方法
print(rep3.content)
print(rep3.text)
print(type(rep3.text))
print(rep3.status_code)
print(rep3.headers)
print(rep3.json())
print(rep3.encoding)

#正确代码是把data进行json编码,再发送。代码如下:

#r = requests.post(url=url,data=json.dumps(data),headers=headers) # 利用 json 对 字典序列化

post 请求中有三种数据提交格式

第一种是表单(application/x-www-form-urlencoded 以表单格式提交数据

data={"fool":"barl","foo2":"bar2"}

response=requests.post(url="https://postman-echo.com/post",data =data)

print(response.text)

data={"fool":"barl","foo2":"bar2"}

response=requests.post(url="https://postman-echo.com/post",data =data)

print(response.text)

第二种是json格式,-application/json

data={"fool":"barl","foo2":"bar2"}

response1=requests.post(url="https://postman-echo.com/post", json=data)

response2=requests.post(url="https://postman-echo.com/post", data=json.dumps(data))

data={"fool":"barl","foo2":"bar2"}

response1=requests.post(url="https://postman-echo.com/post", json=data)

response2=requests.post(url="https://postman-echo.com/post", data=json.dumps(data))

第三种是上传文件格式 -multipart/form-data

headers=""
files={"file":open("test_file.txt","rb")}
response3=requests.post("https://postman-echo.com/post",files=files,headers=headers)

print(response3.text)

headers=""

files={"file":open("test_file.txt","rb")}

response3=requests.post("https://postman-echo.com/post",files=files,headers=headers)

print(response3.text)

#备注: rb 代表以二进制读取数据 r 以人工书写读取数据

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/769117.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号