版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012050154/article/details/81215734
1、json格式的请求
#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
2、原生form表单格式
#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