http协议中几种传递数据方式
一 、application/x-www-form-urlencoded
1 requests.post(url='',data={'key1':'value1','key2':'value2'},headers={'Content-Type':'application/x-www-form-urlencoded'})
♦Reqeusts支持以form表单形式发送post请求,只需要将请求的参数构造成一个字典,然后传给requests.post()的data参数即可。
url = 'http://httpbin.org/post'
d = {'key1': 'value1', 'key2': 'value2'}
r = requests.post(url, data=d)
print r.text
二、multipart/form-data
除了传统的application/x-www-form-urlencoded
表单,我们另一个经常用到的是上传文件用的表单,这种表单的类型为multipart/form-data
。
形式:
1 requests.post(url='',data={'key1':'value1','key2':'value2'},headers={'Content-Type':'multipart/form-data'})
代码
from requests_toolbelt import MultipartEncoder
import requests
m = MultipartEncoder(
fields={'field0': 'value', 'field1': 'value',
'field2': ('filename', open('file.py', 'rb'), 'text/plain')}
)
r = requests.post('http://httpbin.org/post', data=m,
headers={'Content-Type': m.content_type})
三、application/json
请求正文是raw
♦传入xml格式文本
requests.post(url='',data='<?xml ?>',headers={'Content-Type':'text/xml'})
♦传入json格式文本
requests.post(url='',data=json.dumps({'key1':'value1','key2':'value2'}),headers={'Content-Type':'application/json'})
四、text/xml
请求正文是binary
1 requests.post(url='',files={'file':open('test.xls','rb')},headers={'Content-Type':'binary'})
网友评论