“Content-Type”: “application/x-www-form-urlencoded”,
……
},
“json”: null,
……
}
可以看到,请求头中的Content-Type字段已设置为application/x-www-form-urlencoded
,且d = {'key1': 'value1', 'key2': 'value2'}
以form表单的形式提交到服务端,服务端返回的form字段即是提交的数据。
(2)请求正文是multipart/form-data
除了传统的application/x-www-form-urlencoded
表单,我们另一个经常用到的是上传文件用的表单,这种表单的类型为multipart/form-data
。
形式:
requests.post(url=‘’,data={‘key1’:‘value1’,‘key2’:‘value2’},headers={‘Content-Type’:‘multipart/form-data’})
发送文件中的数据需要(安装requests_toolbelt)
‘’’
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
‘’’
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})
不需要文件
from requests_toolbelt import MultipartEncoder
import requests
m = MultipartEncoder(fields={‘field0’: ‘value’, ‘field1’: ‘value’})
r = requests.post(‘http://httpbin.org/post’, data=m,
headers={‘Content-Type’: m.content_type})
(3)请求正文是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’})
或者:
requests.post(url=‘’,json={{‘key1’:‘value1’,‘key2’:‘value2’}},headers={‘Content-Type’:‘application/json’})
- 可以将一json串传给requests.post()的data参数,
输入:
url = ‘http://httpbin.org/post’
s = json.dumps({‘key1’: ‘value1’, ‘key2’: ‘value2’})
r = requests.post(url, data=s)
print r.text
输出:
{
“args”: {},
“data”: “{\”key2\”: \”value2\”, \”key1\”: \”value1\”}”,
“files”: {},
“form”: {},
“headers”: {
……
“Content-Type”: “application/json”,
……
},
“json”: {
“key1”: “value1”,
“key2”: “value2”
},
……
}
(4)请求正文是binary
形式:
requests.post(url=‘’,files={‘file’:open(‘test.xls’,‘rb’)},headers={‘Content-Type’:‘binary’})
- Requests也支持以multipart形式发送post请求,只需将一文件传给requests.post()的files参数即可。
输入:
‘’’
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
‘’’
url = ‘http://httpbin.org/post’
files = {‘file’: open(‘report.txt’, ‘rb’)}
r = requests.post(url, files=files)
print r.text
输出:
{
“args”: {},
“data”: “”,
“files”: {
“file”: “Hello world!”
},
“form”: {},
“headers”: {……
感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的:
① 2000多本Python电子书(主流和经典的书籍应该都有了)
② Python标准库资料(最全中文版)
③ 项目源码(四五十个有趣且经典的练手项目及源码)
④ Python基础入门、爬虫、web开发、大数据分析方面的视频(适合小白学习)
⑤ Python学习路线图(告别不入流的学习)
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!