python发送HTTP请求代码

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

GET 方法    

>>> import httplib  
>>> conn = httplib.HTTPConnection("www.python.org")  
>>> conn.request("GET", "/index.html")  
>>> r1 = conn.getresponse()  
>>> print r1.status, r1.reason  
200 OK  
>>> data1 = r1.read()  
>>> conn.request("GET", "/parrot.spam")  
>>> r2 = conn.getresponse()  
>>> print r2.status, r2.reason  
404 Not Found  
>>> data2 = r2.read()  
>>> conn.close() 

HEAD 方法    

>>> import httplib  
>>> conn = httplib.HTTPConnection("www.python.org")  
>>> conn.request("HEAD","/index.html")  
>>> res = conn.getresponse()  
>>> print res.status, res.reason  
200 OK  
>>> data = res.read()  
>>> print len(data)  
0 
>>> data == ''  
True 

[代码]POST 方法    

>>> import httplib, urllib  
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})  
>>> headers = {"Content-type": "application/x-www-form-urlencoded",  
...            "Accept": "text/plain"}  
>>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80")  
>>> conn.request("POST", "/cgi-bin/query", params, headers)  
>>> response = conn.getresponse()  
>>> print response.status, response.reason  
200 OK  
>>> data = response.read()  
>>> conn.close() 

标签: 代码

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:使用Python访问并下载网页内容的代码

下一篇:Python压缩文件夹/解压缩zip文件