【python】發送post請求

1. json格式的post請求json

關鍵部分加粗顯示了,主要是post數據的編碼方式以及請求頭的Content-typeflask

#coding=utf8
import json
import gzip
import msgpack
import urllib
import urllib2
import tarfile

def request():
    try:
        url = "http://10.11.12.13/abc/def"
        values = {"a":1, "b":2, "c":3, "d":4}
        data = json.JSONEncoder().encode(values) print data
        user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
        headers = {'User-Agent' : user_agent, 'Content-type':"application/json"}
        req = urllib2.Request(url, data=data, headers=headers)
        res_data = urllib2.urlopen(req)
        res = res_data.read()

        print "response:" + str(len(res))
        if res_data.getcode() == 200:
            return res
    except urllib2.HTTPError, err:
        print(err.code)
        print(err.read())
        raise

 

相應的flask獲取數據方式:瀏覽器

req_data = request.get_data()
json_data = json.loads(req_data)
a = json_data['a']
b = json_data['b']

 

 

2. 瀏覽器的原生form表單格式,對應 Content-type:application/x-www-form-urlencodedapp

#coding=utf8
import json
import gzip
import msgpack
import urllib
import urllib2
import tarfile

def request():
    try:
        url = "http://10.11.12.13/abc/def"
        values = {"a":1, "b":2, "c":3, "d":4}
        data = urllib.urlencode(values) print data
        req = urllib2.Request(url, data)
        res_data = urllib2.urlopen(req)
        res = res_data.read()

        print "response:" + str(len(res))
        if res_data.getcode() == 200:
            return res
    except urllib2.HTTPError, err:
        print(err.code)
        print(err.read())
        raise

能夠看到,主要區別是數據編碼方式不一樣。post

相關文章
相關標籤/搜索