HTTP 协议规定 POST 提交的数据必须放在消息主体(entity-body)中,但协议并无规定数据必须使用什么编码方式。常见的四种编码方式以下:
一、application/x-www-form-urlencoded
这应该是最多见的 POST 提交数据的方式了。浏览器的原生 form 表单,若是不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded 方式提交数据。请求相似于下面这样(无关的请求头在本文中都省略掉了):python
POST http://www.example.com HTTP/1.1 Content-Type: application/x-www-form-urlencoded;charset=utf-8 title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3
二、multipart/form-data
这又是一个常见的 POST 数据提交的方式。咱们使用表单上传文件时,必须让 form 的 enctyped 等于这个值,下面是示例chrome
POST http://www.example.com HTTP/1.1 Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA ------WebKitFormBoundaryrGKCBY7qhFd3TrwA Content-Disposition: form-data; name="text" title ------WebKitFormBoundaryrGKCBY7qhFd3TrwA Content-Disposition: form-data; name="file"; filename="chrome.png" Content-Type: image/png PNG ... content of chrome.png ... ------WebKitFormBoundaryrGKCBY7qhFd3TrwA--
三、application/json
application/json 这个 Content-Type 做为响应头你们确定不陌生。实际上,如今愈来愈多的人把它做为请求头,用来告诉服务端消息主体是序列化后的 JSON 字符串。因为 JSON 规范的流行,除了低版本 IE 以外的各大浏览器都原生支持 JSON.stringify,服务端语言也都有处理 JSON 的函数,使用 JSON 不会赶上什么麻烦。json
四、text/xml
它是一种使用 HTTP 做为传输协议,XML 做为编码方式的远程调用规范。浏览器
那么Python在调用外部http请求时,post请求怎么传请求体呢?说实话楼主只实践过【一、application/x-www-form-urlencoded】【二、multipart/form-data 】和【三、application/json】
1、application/x-www-form-urlencodedmarkdown
import urllib
url = "http://www.example.com" body_value = {"package": "com.tencent.lian","version_code": "66" } body_value = urllib.urlencode(body_value) request = urllib2.Request(url, body_value) request.add_header(keys, headers[keys]) result = urllib2.urlopen(request ).read()
2、multipart/form-data
须要利用python的poster模块,安装poster:pip install poster
代码:app
from poster.encode import multipart_encode from poster.streaminghttp import register_openers url = "http://www.example.com" body_value = {"package": "com.tencent.lian","version_code": "66" } register_openers() datagen, re_headers = multipart_encode(body_value) request = urllib2.Request(url, datagen, re_headers) # 若是有请求头数据,则添加请求头 request .add_header(keys, headers[keys]) result = urllib2.urlopen(request ).read()
2、application/json函数
import json
url = "http://www.example.com" body_value = {"package": "com.tencent.lian","version_code": "66" } register_openers() body_value = json.JSONEncoder().encode(body_value) request = urllib2.Request(url, body_value) request .add_header(keys, headers[keys]) result = urllib2.urlopen(request ).read()