python HTTP请求---使用urllib2

1.GET请求

具体GET实例如下:

#!/usr/bin/python

import urllib2
import json



url="http://my.oms/api/notification/?format=json&page_size=10"

req=urllib2.Request(url)

# token
token='3c04c16d3d361db3bd4511803bbc8aad36795788'
req.add_header('Authorization', 'token %s' % token)
print "req:%s" %req.headers

try:
    resp=urllib2.urlopen(req)
except urllib2.HTTPError, e:
    print e.code,e.message
    exit()

# response header
resp_header = resp.info()
print "header:%s" % resp_header

# response content
origin_data=resp.read()
data=json.loads(origin_data)
print "data:%s" %data

2.POST 请求

具体代码实例如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import urllib, urllib2
import json

#ip:port OK
#event_url = "http://10.8.39.58:80/api/notification/"
event_url = "http://my.oms/api/notification/"


# request
req=urllib2.Request(event_url)

# attach data
post_param = {
    'level_id': 300,
    'type_id': 1,
    'source_id':2,
    'title': "测试",
    'message':'测试邮件,请查看。',
    'pool_id':1086,
    'ignore':'5',
    'caller':"130**006"
}


post_param_data = urllib.urlencode(post_param)
req.add_data(post_param_data)

print "req:%s" %req

# begin
try:
    resp=urllib2.urlopen(req, timeout=60)
except urllib2.HTTPError as e:
    print "http error...."
    print e
    print e.code
    #print e.read()
    print e.reason
    exit()
except urllib2.URLError as  e:
    print e
    print e.code
    print e.reason
    #print e.read()
    exit()



# response
code = resp.getcode()
resp_data=resp.read()

print "ret code:", code
print "resp_data: ",resp_data
print "Well done..."

参考

http://unixman.blog.51cto.com/10163040/1654727
http://www.jb51.net/article/51941.htm

其他

比较来说,requests的使用更为简单,有关requests的使用可以参考
http://blog.csdn.net/lanyang123456/article/details/72594982

你可能感兴趣的:(python)