python实现http post四种请求体x-www-form-urlencoded , form-data, json, xml

转载自:yunshouhu 的博客

HTTP 协议规定 POST 提交的数据必须放在消息主体(entity-body)中,但协议并没有规定数据必须使用什么编码方式。常见的四种编码方式如下:

1、application/x-www-form-urlencoded

这应该是最常见的 POST 提交数据的方式了。浏览器的原生 form 表单,如果不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded 方式提交数据。请求类似于下面这样(无关的请求头在本文中都省略掉了):

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

2、multipart/form-data

这又是一个常见的 POST 数据提交的方式。我们使用表单上传文件时,必须让 form 的 enctyped 等于这个值,下面是示例

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--

3、application/json

application/json 这个 Content-Type 作为响应头大家肯定不陌生。实际上,现在越来越多的人把它作为请求头,用来告诉服务端消息主体是序列化后的 JSON 字符串。由于 JSON 规范的流行,除了低版本 IE 之外的各大浏览器都原生支持 JSON.stringify,服务端语言也都有处理 JSON 的函数,使用 JSON 不会遇上什么麻烦。

4、text/xml

它是一种使用 HTTP 作为传输协议,XML 作为编码方式的远程调用规范。

那么Python在调用外部http请求时,post请求怎么传请求体呢?说实话楼主只实践过【1、application/x-www-form-urlencoded】【2、multipart/form-data 】和【3、application/json】

一、application/x-www-form-urlencoded

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()

二、multipart/form-data

需要利用python的poster模块,安装poster:pip install poster
代码:

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()

三、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()
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import  sys
import  os
import  urllib
import urllib2
import re
import cookielib
import  json

'''
dic = {'a': 'aa', 'b': 'bb'}
urllib.urlencode(dic)  // dictionary 转成 url 中的参数: a=aa&b=bb
json.dumps(dic)  // dictionary 转成 json: {"a":"aa", "b":"bb"}
'''
def jsonPost(url):
    print url
    print headers
    req=urllib2.Request(url,j_data,headers)
    page=urllib2.urlopen(req)
    result=page.read();
    print result;
    page.close();

headers={}
headers['Content-Type'] = 'application/json; charset=utf-8'


values={}
values['uuid']='xxx';
values['uid']='1234'
route='login'
port=8888
post_data=urllib.urlencode(values)
j_data=json.dumps(values);
print j_data

#pip install poster
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
#application/x-www-form-urlencoded
def test001():
    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()

#multipart/form-data
def test002():
    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()

#application/json
def test003():
    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()

test001();
test002();
test003();

#res = jsonPost("http://127.0.0.1:%s/%s" % (port, route))
#print res

猜你喜欢

转载自blog.csdn.net/qq_37049781/article/details/82386426