python通過httplib發送GET和POST請求代碼

jopen 9年前發布 | 3K 次閱讀 Python

python有一個httplib的庫,提供了很方便的方法實現GET和POST請求,只需要簡單的組織一下即可。

python發送get請求代碼:

#!/usr/bin/env python

coding=utf8

import httplib

httpClient = None

try: httpClient = httplib.HTTPConnection('localhost', 80, timeout=30) httpClient.request('GET', '/test.php')

#response是HTTPResponse對象
response = httpClient.getresponse()
print response.status
print response.reason
print response.read()

except Exception, e: print e finally: if httpClient: httpClient.close()</pre>
發送POST請求

#!/usr/bin/env python

coding=utf8

import httplib, urllib

httpClient = None try: params = urllib.urlencode({'name': 'tom', 'age': 22}) headers = {"Content-type": "application/x-www-form-urlencoded" , "Accept": "text/plain"}

httpClient = httplib.HTTPConnection("localhost", 80, timeout=30)
httpClient.request("POST", "/test.php", params, headers)

response = httpClient.getresponse()
print response.status
print response.reason
print response.read()
print response.getheaders() #獲取頭信息

except Exception, e: print e finally: if httpClient: httpClient.close()</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!