在接收并解释请求消息后,服务器以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>