这篇文章主要介绍了 Python 使用 requests 发送 POST 请求实例代码, 小编觉得还是挺不错的, 具有一定借鉴价值, 需要的朋友可以参考下
本文研究的主要是 Python 使用 requests 发送 POST 请求的相关内容, 具体介绍如下
一个 http 请求包括三个部分, 为别为请求行, 请求报头, 消息主体, 类似以下这样:
请求行
请求报头
消息主体
HTTP 协议规定 post 提交的数据必须放在消息主体中, 但是协议并没有规定必须使用什么编码方式服务端通过是根据请求头中的 Content-Type 字段来获知请求中的消息主体是用何种方式进行编码, 再对消息主体进行解析具体的编码方式包括:
application / x - www - form - urlencoded
最常见 post 提交数据的方式, 以 form 表单形式提交数据
application/json
以 json 串提交数据
multipart/form-data
一般使用来上传文件
2.7.1 以 form 形式发送 post 请求
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
输出:
- {
- args: {},
- data: ,
- files: {},
- form: {
- key1: value1,
- key2: value2
- },
- headers: {
- Content - Type: application / x - www - form - urlencoded,
- },
- json: null,
- }
可以看到, 请求头中的 Content-Type 字段已设置为 application/x-www-form-urlencoded, 且 d = {'key1': 'value1', 'key2': 'value2'} 以 form 表单的形式提交到服务端, 服务端返回的 form 字段即是提交的数据
2.7.2 以 json 形式发送 post 请求
可以将一 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
- },
- }
可以看到, 请求头的 Content-Type 设置为 application/json, 并将 s 这个 json 串提交到服务端中
2.7.3 以 multipart 形式发送 post 请求
Requests 也支持以 multipart 形式发送 post 请求, 只需将一文件传给 requests.post() 的 files 参数即可
- 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: {
- Content-Type: multipart/form-data; boundary=467e443f4c3d403c8559e2ebd009bf4a,
- },
- json: null,
文本文件 report.txt 的内容只有一行: Hello world!, 从请求的响应结果可以看到数据已上传到服务端中
总结
以上就是本文关于 Python 使用 requests 发送 POST 请求实例代码的全部内容, 希望对大家有所帮助感兴趣的朋友可以继续参阅本站其他相关专题, 如有不足之处, 欢迎留言指出感谢朋友们对本站的支持!
来源: http://www.phperz.com/article/18/0210/363259.html