python requests解析
来源:互联网 发布:棋牌软件开发定制 编辑:程序博客网 时间:2024/06/14 14:15
原文链接:http://blog.csdn.net/junli_chen/article/details/53670887
一个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!,从请求的响应结果可以看到数据已上传到服务端中。
注:requests从2.4.2开始支持json=...参数代替data=json.dumps(...)
pip install --upgrade requests
原文链接:http://blog.csdn.net/junli_chen/article/details/53670887
- python requests解析
- python requests
- python requests
- Python Requests
- python Requests
- python Requests
- python requests
- Requests-Python
- Python requests库解析中文网页乱码处理方法
- python requests 高级用法
- Python Requests快速入门
- python-requests包
- Python Requests快速入门
- Python模块学习 - Requests
- python中的requests使用
- Python - cookielib [urllib2/requests]
- Python Requests简单运用
- python requests插件
- 生信脚本练习(7)求fastq文件质量值分布
- MATLAB 绘制3D Surf
- 剑指offer--对称的二叉树
- HDU-4614:Vases and Flowers(线段树+二分)
- [LeetCode] 38. Count and Say
- python requests解析
- 【Shiro】--- 简介
- POJ 2955 Brackets 区间DP
- ZOJ 1516 Uncle Tom's Inherited Land (二分图匹配)
- 【转载】机器学习计算距离和相似度的方法
- 剑指offer--按之字形顺序打印二叉树
- 引用数据类型---数组
- R
- 生信脚本练习(8)合并文件 ①