在接收並解釋請求消息後,伺服器以HTTP回應消息回應 -
- 一個狀態行。
- 零個或多個標頭(General | Response | Entity)字段後跟CRLF。
- 空行(即,CRLF之前沒有任何內容的行),表示標頭字段的結尾。
- 可選的消息體。
以下部分解釋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應用程式來理解所有已註冊狀態代碼的含義。
回應標題字段
回應標頭字段允許伺服器傳遞有關無法放入狀態行的回應的其他資訊。這些頭字段提供有關伺服器的資訊以及有關Request-URI
標識的資源的進一步訪問。
- Accept-Ranges
- Age
- ETag
- Location
- Proxy-Authenticate
- Retry-After
- Server
- Vary`
-
WWW-Authenticate`
如果您希望編寫自己的自定義Web客戶端和服務器,可以引入自定義字段。
回應消息示例
下麵我們把它們放在一起,形成一個HTTP回應,用於從在xuhuhu.com
上運行的web伺服器獲取hello.html
頁面的請求 -
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2019 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2019 19:15:56 GMT
Content-Length: 88
Content-Type: text/html
Connection: Closed
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
以下是當Web伺服器找不到請求的頁面時,HTTP回應消息顯示錯誤情況的示例 -
HTTP/1.1 404 Not Found
Date: Sun, 18 Oct 2019 10:36:20 GMT
Server: Apache/2.2.14 (Win32)
Content-Length: 230
Connection: Closed
Content-Type: text/html; charset = iso-8859-1
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>Not Found</h1>
<p>The requested URL /xuhuhu.com.html was not found on this server.</p>
</body>
</html>
以下是HTTP回應消息的示例,顯示Web伺服器在給定HTTP請求中遇到錯誤的HTTP版本時的錯誤情況 -
HTTP/1.1 400 Bad Request
Date: Sun, 18 Oct 2019 10:36:20 GMT
Server: Apache/2.2.14 (Win32)
Content-Length: 230
Content-Type: text/html; charset = iso-8859-1
Connection: Closed
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>400 Bad Request</title>
</head>
<body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<p>
<p>The request line contained invalid characters following the protocol string.<p>
</body>
</html>