python實現http post四種請求體x-www-form-urlencoded ,form-data ,json,xml
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