标签:
python urllib2使用心得
1、http GET请求
过程:获取返回结果,关闭连接,打印结果
f = urllib2.urlopen(req, timeout=10)
the_page = f.read()
f.close()
print the_page
2、http GET请求 + 包头
paras = "Token=1234567890;Uuid=0987654321"
send_headers = {"Cookie": paras, "User-Agent": "mixh5monitor", "Content-Type": "application/json"}
req = urllib2.Request(url, headers=send_headers) # 包头
f = urllib2.urlopen(req, timeout=10) # 包体
the_page = f.read()
f.close()
print the_page
3、http GET请求 + 包头,处理返回响应包头
paras = "Token=1234567890;Uuid=0987654321"
send_headers = {"Cookie": paras, "User-Agent": "mixh5monitor", "Content-Type": "application/json"}
req = urllib2.Request(url, headers=send_headers) # 包头
f = urllib2.urlopen(req, timeout=10) # 包体
response_head = f.info().getheader("Content-Type") # 获取返回包头中Content-Type内容
print response_head
f.close()
4、http POST请求
postdata = urllib.urlencode({"username": "test", "password": "123456", "type": "Z"})
f = opener.open(url, postdata, timeout=10)
the_page = f.read()
f.close()
print the_page
5、http POST请求 + 包头
postdata = urllib.urlencode({"username": "test", "password": "123456", "type": "Z"})
paras = "Token=1234567890;Uuid=0987654321"
send_headers = {"Cookie": paras, "User-Agent": "mixh5monitor", "Content-Type": "application/json"}
req = urllib2.Request(url, headers=send_headers) # 包头
f = opener.open(req, postdata, timeout=10)
the_page = f.read()
f.close()
print the_page
6、http POST请求 + 包头,处理返回响应包头
postdata = urllib.urlencode({"username": "test", "password": "123456", "type": "Z"})
paras = "Token=1234567890;Uuid=0987654321"
send_headers = {"Cookie": paras, "User-Agent": "mixh5monitor", "Content-Type": "application/json"}
req = urllib2.Request(url, headers=send_headers) # 包头
f = opener.open(req, postdata, timeout=10)
response_head = f.info().getheader("Cookie") # 获取返回包头中Cookie内容
print response_head
f.close()
http包头、包体的学习参考: http://www.cnblogs.com/shhnwangjian/p/5110304.html
标签:
原文地址:http://www.cnblogs.com/shhnwangjian/p/5341483.html