首页 > 代码库 > 【python】发送post请求
【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=http://www.mamicode.com/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 =http://www.mamicode.com/ 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
可以看到,主要区别是数据编码方式不同。
【python】发送post请求
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。