【python】发送post请求

1. json格式的post请求

关键部分加粗显示了,主要是post数据的编码方式以及请求头的Content-type

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

#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

可以看到,主要区别是数据编码方式不同。

原文地址:https://www.cnblogs.com/dplearning/p/6230906.html