
- Python - 網路程式設計
- Python - 網路入門
- Python - 網路環境
- Python - 網際網路協議
- Python - IP 地址
- Python - DNS 查詢
- Python - 路由
- Python - HTTP 請求
- Python - HTTP 響應
- Python - HTTP 頭部
- Python - 自定義 HTTP 請求
- Python - 請求狀態碼
- Python - HTTP 認證
- Python - HTTP 資料下載
- Python - 連線重用
- Python - 網路介面
- Python - 套接字程式設計
- Python - HTTP 客戶端
- Python - HTTP 伺服器
- Python - 構建 URL
- Python - Web 表單提交
- Python - 資料庫和 SQL
- Python - Telnet
- Python - 郵件訊息
- Python - SMTP
- Python - POP3
- Python - IMAP
- Python - SSH
- Python - FTP
- Python - SFTP
- Python - Web 伺服器
- Python - 上傳資料
- Python - 代理伺服器
- Python - 目錄列表
- Python - 遠端過程呼叫
- Python - RPC JSON 伺服器
- Python - Google 地圖
- Python - RSS Feed
Python - HTTP 響應
HTTP 或超文字傳輸協議基於客戶端-伺服器模型。通常,Web 瀏覽器是客戶端,託管網站的計算機是伺服器。伺服器在收到客戶端的請求後,會生成響應並以特定格式將其傳送回客戶端。
伺服器在接收和解釋請求訊息後,會以 HTTP 響應訊息進行響應。
- A Status-line
- Zero or more header (General|Response|Entity) fields followed by CRLF
- An empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields
- Optionally a message-body
以下部分解釋了 HTTP 響應訊息中使用的每個實體。
訊息狀態行
狀態行由協議版本、數字狀態碼及其關聯的文字短語組成。這些元素用空格 SP 字元分隔。
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
HTTP 版本
支援 HTTP 版本 1.1 的伺服器將返回以下版本資訊。
HTTP-Version = HTTP/1.1
狀態碼
狀態碼元素是一個 3 位整數,其中狀態碼的第一位定義了響應的類別,後兩位沒有任何分類作用。第一位有 5 個值。
序號 | 程式碼和描述 |
---|---|
1 | 1xx: 資訊性 表示請求已收到,並且處理仍在繼續。 |
2 | 2xx: 成功 表示操作已成功接收、理解並接受。 |
3 | 3xx: 重定向 表示必須採取進一步的操作才能完成請求。 |
4 | 4xx: 客戶端錯誤 表示請求包含語法錯誤或無法完成。 |
5 | 5xx: 伺服器錯誤 表示伺服器未能完成一個明顯有效的請求。 |
HTTP 狀態碼是可擴充套件的,HTTP 應用程式不需要理解所有已註冊狀態碼的含義。
使用 Python Requests
在下面的 Python 程式中,我們使用 urllib3 模組發出 HTTP GET 請求並接收包含資料的響應。它還提供響應程式碼,該程式碼也由模組中的函式管理。PoolManager 物件處理連線池的所有細節,並處理執行緒安全。
import urllib3 http = urllib3.PoolManager() resp = http.request('GET', 'https://tutorialspoint.tw/robots.txt') print resp.data # get the status of the response print resp.status
執行上述程式後,我們得到以下輸出:
User-agent: * Disallow: /tmp Disallow: /logs Disallow: /rate/* Disallow: /cgi-bin/* Disallow: /videotutorials/video_course_view.php?* Disallow: /videotutorials/course_view.php?* Disallow: /videos/* Disallow: /*/*_question_bank/* Disallow: //*/*/*/*/src/* 200
廣告