RESTful服务最佳实践——(十二)

来源:互联网 发布:大华电子秤数据下传 编辑:程序博客网 时间:2024/06/04 19:55

HTTP状态码

以下是大多数由RESTful服务或API返回的常用HTTP状态码,并带有它们普遍用法的简短总结。其他HTTP状态码偶尔使用,但是更专业或更先进。多数服务套件只支持这些常用的状态码,甚至只支持子集,从而维护良好。

200 (OK) – 通常的成功状态。表示成功的最常见代码。

201 (CREATED) – (通过POST或PUT)产生成功的创建。 设置定位头,以存储指向最新创建的资源的链接。

204 (NO CONTENT) – 封装过的响应没有使用,或请求体中没有任何东西时(如DELETE),使用该状态。

304 (NOT MODIFIED) – 用于有条件的GET调用的响应,以减少带宽的使用。 如果该状态被使用,那么必须为通常GET调用中的内容,设置时间、Content-Location、Etag头。必须没有响应体。

400 (BAD REQUEST) – 用于执行请求时可能引起无效状态的一般错误代码。如域名无效错误、数据丢失等,都是一些例子。

401 (UNAUTHORIZED) – 用于缺失或无效认证令牌的错误代码。

403 (FORBIDDEN) – 未授权的用户执行操作,没有权限访问资源,或者资源由于某些原因(如时间约束等)不可用,使用该错误码。

404 (NOT FOUND) – 无论资源存不存在,无论是否有401、403的限制,当请求的资源找不到时,出于安全因素考虑,服务器希望用404掩盖。

409 (CONFLICT) – 每当执行请求可能引起资源冲突时使用。例如,存在重复的实体,或级联删除不支持时删除根对象。

500 (INTERNAL SERVER ERROR) – 当服务器抛出异常时,捕捉到的一般错误。


原文如下


HTTP Status Codes (Top 10)

Below are the most commonly-used HTTP status codes returned from RESTful services or APIs along with a brief summary of their commonly-accepted usage. Other HTTP status codes are used occasionally, but are either specializations or more advanced. Most service suites are well served by supporting only these, or even a sub-set.

200 (OK) – General success status code. Most common code to indicate success.

201 (CREATED) – Successful creation occurred (via either POST or PUT). Set the Location header to contain a link to the newly-created resource. Response body content may or may not be present.

204 (NO CONTENT) – Status when wrapped responses are not used and nothing is in the body (e.g. DELETE).

304 (NOT MODIFIED) – Used in response to conditional GET calls to reduce band-width usage. If used, must set the Date, Content-Location, Etag headers to what they would have been on a regular GET call. There must be no response body.

400 (BAD REQUEST) – General error when fulfilling the request would cause an invalid state. Domain validation errors, missing data, etc. are some examples.

401 (UNAUTHORIZED) – Error code for a missing or invalid authentication token.

403 (FORBIDDEN) – Error code for user not authorized to perform the operation, doesn’t have rights to access the resource, or the resource is unavailable for some reason (e.g. time constraints, etc.).

404 (NOT FOUND) – Used when the requested resource is not found, whether it doesn’t exist or if there was a 401 or 403 that, for security reasons, the service wants to mask.

409 (CONFLICT) – Whenever a resource conflict would be caused by fulfilling the request. Duplicate entries, deleting root objects when cascade-delete not supported are a couple of examples.

500 (INTERNAL SERVER ERROR) – The general catch-all error when the server-side throws an exception.

0 0