python用httplib模組發送get和post請求

來源:互聯網
上載者:User

標籤:

在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 efinally:    if httpClient:        httpClient.close()

上面代碼中使用了finally來保證即使出錯的時候也能關閉httpClient。運行這個程式,在我的電腦上輸出結果如下:

python用httplib發送get請求

2、python發送POST請求

修改test.php內容,列印出$_POST數組:

1 var_dump($_POST);

python發起post請求代碼:

123456789101112131415161718192021222324 #!/usr/bin/env python#coding=utf8 import httplib, urllib httpClient = Nonetry:    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 efinally:    if httpClient:        httpClient.close()

運行代碼,在我的電腦上輸出如下:

python用httplib發送post請求

python用httplib模組發送get和post請求

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.