python HTTP请求---使用urllib2
来源:互联网 发布:伴奏升调降调软件 编辑:程序博客网 时间:2024/05/29 09:50
1.GET请求
具体GET实例如下:
#!/usr/bin/pythonimport urllib2import jsonurl="http://my.oms/api/notification/?format=json&page_size=10"req=urllib2.Request(url)# tokentoken='3c04c16d3d361db3bd4511803bbc8aad36795788'req.add_header('Authorization', 'token %s' % token)print "req:%s" %req.headerstry: resp=urllib2.urlopen(req)except urllib2.HTTPError, e: print e.code,e.message exit()# response headerresp_header = resp.info()print "header:%s" % resp_header# response contentorigin_data=resp.read()data=json.loads(origin_data)print "data:%s" %data
2.POST 请求
具体代码实例如下:
#!/usr/bin/python# -*- coding: utf-8 -*-import urllib, urllib2import json#ip:port OK#event_url = "http://10.8.39.58:80/api/notification/"event_url = "http://my.oms/api/notification/"# requestreq=urllib2.Request(event_url)# attach datapost_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# begintry: 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()# responsecode = resp.getcode()resp_data=resp.read()print "ret code:", codeprint "resp_data: ",resp_dataprint "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
阅读全文
0 0
- python HTTP请求---使用urllib2
- python使用urllib2发送http请求
- Python 使用urllib2 发送http请求 报错503 service unavailable问题
- python urllib2 实现HTTP 的GET POST 请求
- python 使用urllib2发送get请求和post请求
- 解决python使用urllib2不能随意修改HTTP method办法
- python通过get方式,post方式发送http请求和接收http响应-urllib urllib2
- python通过get方式,post方式发送http请求和接收http响应-urllib urllib2
- python通过get方式,post方式发送http请求和接收http响应-urllib urllib2
- python通过get方式,post方式发送http请求和接收http响应-urllib urllib2
- python通过get方式,post方式发送http请求和接收http响应-urllib urllib2
- python urllib2使用细节
- python urllib2, urllib使用
- Python-urllib2的使用
- Python:urllib2使用总结
- python---urllib2使用
- python---urllib2使用代理
- python关于httplib、httplib2、urllib、urllib2、request、socket库,发送http请求
- 第一场个人训练赛
- NAT技术与代理服务器调研
- 查看女神图片
- Git 指令备忘
- MarkDown常用语法
- python HTTP请求---使用urllib2
- 3.表单标签
- JS中String对象与Array对象常用基础知识
- linux性能 --》load average解读
- LeetCode 70 Climbing Stairs
- unity3d安装后打开失败(crashes while startup after install)
- 关于Android方法数量限制的问题
- Lua Function学习
- 解决android studio 中SVN和git冲突 无法提交代码