首先,看一下post请求示例:
r = requests.post("http://pythontab.com/postTest", data = {"key":"value"})
,可见,post请求参数是以
data
关键字来传递的.
POST请求方式的编码有3种,具体的编码方式如下:
-
application/x-www-form-urlencoded
: 最常见的post提交数据的方式,以form表单形式提交数据 -
application/json
: 以json格式提交数据 -
multipart/form-data
: 一般使用来上传文件(较少用)
Requests以form表单形式发送post请求,代码如下:
import requests
url = 'http://httpbin.org/post'
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post(url, data = payload)
print(r.url)
print(r.text)
运行结果:
Requests以json形式发送post请求,代码如下:
import requests,json
url = 'http://httpbin.org/post'
payload = {'key1': 'value1', 'key2': 'value2'}
data_json=json.dumps(payload) # dumps:将python对象解码为json 数据
r = requests.post(url, data = data_json)
print(r.url)
print(r.text)
运行结果:
Requests以multipart形式发送post请求,代码如下:
import requests
url = 'http://httpbin.org/post'
files = {'file':open('D://log.txt','rb')}
r = requests.post(url,files = files) # 用关键字files来传入
print(r.url)
print(r.text)
运行结果:
与get类似,post请求也可以加上自定义的headers参数,代码如下:
import requests, json
url = 'https://httpbin.org/post'
headers = {"Connection":'keep-alive',"Host":"httpbin.org"} # 值以字典的形式传入
response = requests.post(url=url,headers=headers) #用关键字headers传入
print(response.text)
运行结果:
下面是取得请求头或响应头的字段信息代码:
import requests, json
url = 'https://httpbin.org/post'
headers = {"Connection":'keep-alive',"Host":"httpbin.org"} # 值以字典的形式传入
response = requests.post(url=url,headers=headers) #用关键字headers传入
print(response.text)
print(response.request.headers) # 打印出请求头
print(response.request.headers['Host']) # 取得请求的Host
print(response.headers) # 打印出响应头
print(response.headers['Connection']) # 取得部分响应头以做判断:
print(response.headers.get('Connection'))#或者这样也可以
运行结果:
版权声明:本文为u013003827原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。