HTTP教程

HTTP 响应

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

状态码

Status-Code 元素是一个 3 位整数,其中 Status-Code 的第一位数字定义响应的类别,最后两位数字没有任何分类作用。第一个数字有 5 个值:
SN 代码和说明
1 1xx: Informational
表示已收到请求,进程正在继续。
2 2xx: Success
表示动作被成功接收、理解和接受。
3 3xx: Redirection
这意味着必须采取进一步的行动才能完成请求。
4 4xx: Client Error
表示请求包含不正确的语法或无法完成。
5 5xx: Server Error
这意味着服务器未能满足明显有效的请求。
HTTP 状态代码是可扩展的,并且 HTTP 应用程序不需要了解所有已注册状态代码的含义。所有状态代码的列表已在单独的章节中提供,供您参考。

响应头字段

当我们学习 HTTP 标头字段时,我们将在单独的章节中学习 General-header 和 Entity-header。现在,让我们检查一下响应头字段是什么。
响应头字段允许服务器传递有关无法放置在状态行中的响应的附加信息。这些标头字段提供有关服务器的信息以及有关进一步访问由 Request-URI 标识的资源的信息。
Accept-Ranges Age ETag Location Proxy-Authenticate Retry-After Server Vary WWW-Authenticate
如果您要编写自己的自定义 Web 客户端和服务器,您可以引入自定义字段。

响应消息示例

现在让我们把它们放在一起形成一个 HTTP 响应,用于从在 tutorialspoint.com 上运行的 Web 服务器获取 hello.htm 页面的请求
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2009 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 2012 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 /t.html was not found on this server.</p>
</body>
</html>
以下是 Web 服务器在给定 HTTP 请求中遇到错误 HTTP 版本时显示错误情况的 HTTP 响应消息示例:
HTTP/1.1 400 Bad Request
Date: Sun, 18 Oct 2012 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>
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4