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

36 篇文章 1 订阅

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

#python http post json
#python实现http post四种请求体application/x-www-form-urlencoded ,multipart/form-data ,application/json,text/xml
#http://www.cnblogs.com/111testing/p/6079565.html
#http://www.cnblogs.com/hangj/p/4720628.html
#res = jsonPost("http://127.0.0.1:%s/%s" % (port, route))
#print res

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值