標籤:
在python中,類比http用戶端發送get和post請求,主要用httplib模組的功能。
1、python發送GET請求
我在本地建立一個測試環境,test.php的內容就是輸出一句話:
1 |
echo ‘Old friends and old wines are best.‘ ; |
python發送get請求代碼:
123456789101112131415161718192021 |
#!/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() |
上面代碼中使用了finally來保證即使出錯的時候也能關閉httpClient。運行這個程式,在我的電腦上輸出結果如下:
python用httplib發送get請求
2、python發送POST請求
修改test.php內容,列印出$_POST數組:
python發起post請求代碼:
123456789101112131415161718192021222324 |
#!/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() |
運行代碼,在我的電腦上輸出如下:
python用httplib發送post請求
python用httplib模組發送get和post請求