跳到主要内容

4.6. 使用 HTTP Status Code

4.6. 使用 HTTP Status Code (Using HTTP Status Codes)

使用 HTTP 的 application MUST 只使用已注册的 HTTP status code. 它们 SHOULD 使用适用的最具体 status code, 尽管不限于 [HTTP] 中定义的 status code; 只要其他 status code 已在 "HTTP Status Codes" registry 中注册, 就可以使用.

规定 status code 如何使用时, application SHOULD 关注其 generic semantics, 而不是它们在特定上下文中的具体含义. 例如, 如下表述是合适的:

如果 request 成功, server 发送 200 OK response.

但如下表述不合适:

当 user 已认证且被授权访问 resource 时, server 发送 200 OK response.

后者过于具体, 因为它混淆了几件事: success, authentication 和 authorization. 更合适的表述是:

如果 request 成功, server 发送 200 OK response. 如果需要 authentication 但未提供, server 发送 401 Unauthorized response. 如果 client 未被授权访问 resource, server 发送 403 Forbidden response.

application SHOULD NOT 定义新的 status code. 在极少数确实需要新 status code 的情况下, 它 MUST 按 [HTTP] Section 16.2 中的过程注册.

选择 status code 时, 一般原则是选择适用的最具体 status code. status code 应传达 response 的主要原因.

例如, 如果 request 因 resource 不存在而失败, 404 Not Found 是合适的. 如果它因 client 未被授权访问而失败, 403 Forbidden 是合适的, 即便该 resource 可能不存在.

application SHOULD 适当地使用以下 status code:

  • 200 OK 用于 response 包含 representation 的成功 request.

  • 201 Created 用于导致创建新 resource 的成功 request.

  • 202 Accepted 用于已接受处理但处理尚未完成的 request.

  • 204 No Content 用于没有 representation 可发送的成功 request.

  • 301 Moved Permanently308 Permanent Redirect 用于已永久移动的 resource.

  • 302 Found307 Temporary Redirect 用于已临时移动的 resource.

  • 304 Not Modified 用于 resource 未变化的 conditional request.

  • 400 Bad Request 用于 malformed request.

  • 401 Unauthorized 用于要求 authentication 的 request.

  • 403 Forbidden 用于 client 未被授权的 request.

  • 404 Not Found 用于针对不存在 resource 的 request.

  • 405 Method Not Allowed 用于使用不适当 method 的 request.

  • 406 Not Acceptable 用于 server 无法生成 client 会接受的 representation 的情况.

  • 409 Conflict 用于 request 与 resource 当前 state 冲突的情况.

  • 410 Gone 用于曾经存在但已被永久移除的 resource.

  • 415 Unsupported Media Type 用于 request 的 Content-Type 不受支持的情况.

  • 500 Internal Server Error 用于 server-side error.

  • 501 Not Implemented 用于 server 不支持所请求 functionality 的情况.

  • 503 Service Unavailable 用于 server 暂时无法处理 request 的情况.