本文实例讲述了python发送http请求的方法。分享给大家供大家参考。具体如下:
这里包含 python 使用 get/head/post 方法进行 http 请求
1. 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()
2. 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
3. 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()
希望本文所述对大家的python程序设计有所帮助。