【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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值