Http code 204

Http code 204

HTTP протокол: основные правила Интернета, которые должен знать каждый веб-разработчик. Как браузер взаимодействует с сервером.

Успешные коды состояния HTTP сервера: 200, 201, 202, 203, 204, 205, 206

Привет, читатель блога ZametkiNaPolyah.ru! Продолжим знакомиться с протоколом HTTP в рубрике серверы и протоколы и ее разделе HTTP протокол. В этой записи мы с тобой рассмотрим успешные коды состояния HTTP сервера, которые, как ты понимаешь, начинаются с двойки. Для начала мы посмотрим на список успешных кодов состояния и дадим и короткое пояснение, а затем мы посмотрим на то, как успешные коды состояния связаны с методами HTTP запроса. В конце этой публикации мы более подробно поговорим про каждый из успешных кодов состояния.

Http code 204. Смотреть фото Http code 204. Смотреть картинку Http code 204. Картинка про Http code 204. Фото Http code 204

Успешные коды состояния HTTP сервера: 200, 201, 202, 203, 204, 205, 206

Общее описание успешных кодов состояния HTTP сервера

Если вы хотите узнать всё про протокол HTTP, обратитесь к навигации по рубрике HTTP протокол. Успешные коды состояния HTTP сервера говорят клиенту о том, что его запрос успешно получен, понят, принят и обработан. Успешные коды состояния HTTP сервера всегда начинаются с двойки, давайте сведем в одну таблицу все успешные HTTP коды, как мы это делали для информационных кодов.

Успешный код состоянияОписание успешного кода состояния HTTP севера
200 OKУспешный код состояния HTTP сервера 200: хорошо

Код состояния 200 говорит клиенту о том, что его запрос удачно выполнен.

201 CreatedУспешный код состояния HTTP сервера 201: создан

Код состояния 201 сообщает нам о том, что новый ресурс был создан успешно.

202 AcceptedУспешный код состояния HTTP сервера 202: принято

Код состояния 202 сообщает клиенту о том, что HTTP запрос успешно принят на обработку, но обработка еще не завершена, в этом случае сервер может отказать в обслуживание запроса клиента.

203 Non-authoritative InformationУспешный код состояния HTTP сервера 203: не авторская информация

Код состояния 203, отправленный в HTTP ответе, сообщает клиенту о том, что возвращенная в заголовке HTTP объекта информация – это не оригинал, который есть на первоначальном сервере, а документ, собранный из локальных копий или копий третьей стороны.

204 No ContentУспешный код состояния HTTP сервера 204: нет содержимого

Код состояния 204 говорит клиенту о том, что в ответном HTTP сообщении нет тела (про тело объекта HTTP).

205 Reset ContentУспешный код состояния HTTP сервера 205: сбросить содержимое

Если браузер получит код состояния 205, то он должен очистить форму, чтобы дать пользователю ввести дополнительные данные.

206 Partial ContentУспешный код состояния HTTP сервера 206: частичное содержимое

Код состояния 206 говорит браузеру о том, что HTTP сервер выполнил частичный GET запрос клиента (про методы HTTP). Чтобы получить такой код запрос клиента должен содержать поле заголовка Range, который указывает диапазон (вспоминаем диапазоны значений и HTTP параметры).

Перейдем к рассмотрению HTTP кодов состояний из класса 2хх (если ты еще не знаешь про классы состояния HTTP)

HTTP код состояния 200 (успешно). HTTP код состояния 201 (создано). HTTP код состояния 202 (принято)

HTTP код состояния 200 сообщает о том, что запрос клиента был успешно принят и обработан. Информация, которая будет возвращена пользователю зависит от метода HTTP запроса. Давайте составим небольшую таблицу с методами и тем, какое содержимое им вернет сервер с HTTP кодом состояния 200.

Метод HTTP запросаСодержимое HTTP ответа с кодом 200
GETВ ответ на метод GET клиент получит HTTP сообщение с кодом 200 и объект, который расположен по указанному URI в запросе (URI в HTTP).
POSTЕсли клиент отправляет запрос методом POST, то в ответ он получает сообщение с кодом состояния 200 с описание объекта или результатом действия метода POST.
TRACEКлиент, отправивший запрос методом TRACE, получит HTTP ответ с кодом состояния 200, который будет содержать сообщение, полученное конечным сервером.
HEADВ ответ на метод HEAD клиент получит сообщение с кодом состояния 200, в котором не будет тела сообщения

HTTP код 200 мы рассмотрели, давайте перейдем к коду 201.

HTTP код состояния 201 сообщает клиенту о том, что запрос успешно выполнен и в результате этого запроса появился новый ресурс по указанному в запросе URI. Но сервер вместо кода 201 может послать код 202 в том случае, если он не может выполнить запрос клиента немедленно. Давайте перейдем к рассмотрению HTTP кода состояния 202.

HTTP код состояния 202 сообщает клиенту о том, что его запрос успешно принят на обработку, но обработка сервером еще не завершена. В итоге сервер может выполнить запрос клиента, а может его отклонить. Ответы с кодом состояния 202 уклончивы и это сделано преднамеренно, например, для того, чтобы дать серверу выполнить какой-то более важный запрос, а потом ответить клиенту, которому он отправлял HTTP сообщение с кодом состояния 202.

HTTP код состояния 203 (не авторская информация). HTTP код состояния 204 (нет содержимого). HTTP код состояния 205 (сбросить содержимое). HTTP код состояния 206 (частичное содержимое)

Перейдем к следующему успешному коду состояния HTTP сервера – код состояния 203, который говорит клиенту о том, что информация не авторская. HTTP код состояния 203 возвращает в заголовке своего сообщения информацию о том, что данное сообщение не является оригиналом, который доступен на первоначальном сервере и, возможно, информация взята из кэша HTTP сервера.

HTTP код состояния 204 говорит клиенту о том, что сервер успешно выполнил запрос, но никакой новой полезной информации нет. HTTP код состояния 204 используется чаще всего для работы с HTML формами для ввода пользовательских данных. Ответ с кодом состояния 204 не должен содержать тела сообщения.

HTTP код состояния 205 говорит браузеру о том, что ему следует (читай требования HTTP) отменить просмотр документа. Такой код состояния HTTP сервера чаще всего используется для очистки форм с целью повторного или последующего ввода и не содержит HTTP объекта.

HTTP код состояния 206 говорит о том, что был выполнен частичный метод GET. Чтобы получить такой код состояния запрос клиента должен содержать поле заголовка Range, в котором указывается диапазон в байтах, при этом ответ HTTP сервера должен содержать поле заголовка Content-Range, либо поле заголовка Content-Type.

Мы рассмотрели успешные коды состояния HTTP, давайте перейдем к кодам перенаправления. Еще есть коды ошибок клиента и коды ошибок сервера, о которых можно узнать на моём сайте. А если тебе нужна информацию обо всех кодах состояния, обратись к справочнику HTTP кодов состояния, в котором есть полное описание всех кодов.

Источник

HTTP response status codes

HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes:

The below status codes are defined by section 10 of RFC 2616. You can find an updated specification in RFC 7231.

Note: If you receive a response that is not in this list, it is a non-standard response, possibly custom to the server’s software.

Information responses

This interim response indicates that the client should continue the request or ignore the response if the request is already finished.

This code is sent in response to an Upgrade request header from the client and indicates the protocol the server is switching to.

This code indicates that the server has received and is processing the request, but no response is available yet.

This status code is primarily intended to be used with the Link header, letting the user agent start preloading resources while the server prepares a response.

Successful responses

The request succeeded. The result meaning of «success» depends on the HTTP method:

The request succeeded, and a new resource was created as a result. This is typically the response sent after POST requests, or some PUT requests.

The request has been received but not yet acted upon. It is noncommittal, since there is no way in HTTP to later send an asynchronous response indicating the outcome of the request. It is intended for cases where another process or server handles the request, or for batch processing.

This response code means the returned metadata is not exactly the same as is available from the origin server, but is collected from a local or a third-party copy. This is mostly used for mirrors or backups of another resource. Except for that specific case, the 200 OK response is preferred to this status.

There is no content to send for this request, but the headers may be useful. The user agent may update its cached headers for this resource with the new ones.

Tells the user agent to reset the document which sent this request.

This response code is used when the Range header is sent from the client to request only part of a resource.

Conveys information about multiple resources, for situations where multiple status codes might be appropriate.

Used inside a response element to avoid repeatedly enumerating the internal members of multiple bindings to the same collection.

The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.

Redirection messages

The request has more than one possible response. The user agent or user should choose one of them. (There is no standardized way of choosing one of the responses, but HTML links to the possibilities are recommended so the user can pick.)

The URL of the requested resource has been changed permanently. The new URL is given in the response.

This response code means that the URI of requested resource has been changed temporarily. Further changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.

The server sent this response to direct the client to get the requested resource at another URI with a GET request.

This is used for caching purposes. It tells the client that the response has not been modified, so the client can continue to use the same cached version of the response.

Defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy.

This response code is no longer used; it is just reserved. It was used in a previous version of the HTTP/1.1 specification.

The server sends this response to direct the client to get the requested resource at another URI with same method that was used in the prior request. This has the same semantics as the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.

This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.

Client error responses

The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

Although the HTTP standard specifies «unauthorized», semantically this response means «unauthenticated». That is, the client must authenticate itself to get the requested response.

This response code is reserved for future use. The initial aim for creating this code was using it for digital payment systems, however this status code is used very rarely and no standard convention exists.

The server can not find the requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 Forbidden to hide the existence of a resource from an unauthorized client. This response code is probably the most well known due to its frequent occurrence on the web.

The request method is known by the server but is not supported by the target resource. For example, an API may not allow calling DELETE to remove a resource.

This response is sent when the web server, after performing server-driven content negotiation, doesn’t find any content that conforms to the criteria given by the user agent.

This is similar to 401 Unauthorized but authentication is needed to be done by a proxy.

This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message.

This response is sent when a request conflicts with the current state of the server.

This response is sent when the requested content has been permanently deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for «limited-time, promotional services». APIs should not feel compelled to indicate resources that have been deleted with this status code.

Server rejected the request because the Content-Length header field is not defined and the server requires it.

The client has indicated preconditions in its headers which the server does not meet.

Request entity is larger than limits defined by server. The server might close the connection or return an Retry-After header field.

The URI requested by the client is longer than the server is willing to interpret.

The media format of the requested data is not supported by the server, so the server is rejecting the request.

The range specified by the Range header field in the request cannot be fulfilled. It’s possible that the range is outside the size of the target URI’s data.

This response code means the expectation indicated by the Expect request header field cannot be met by the server.

The server refuses the attempt to brew coffee with a teapot.

The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.

The request was well-formed but was unable to be followed due to semantic errors.

The resource that is being accessed is locked.

The request failed due to failure of a previous request.

Indicates that the server is unwilling to risk processing a request that might be replayed.

The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server sends an Upgrade header in a 426 response to indicate the required protocol(s).

The origin server requires the request to be conditional. This response is intended to prevent the ‘lost update’ problem, where a client GET s a resource’s state, modifies it and PUT s it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.

The user has sent too many requests in a given amount of time («rate limiting»).

The server is unwilling to process the request because its header fields are too large. The request may be resubmitted after reducing the size of the request header fields.

The user agent requested a resource that cannot legally be provided, such as a web page censored by a government.

Server error responses

The server has encountered a situation it does not know how to handle.

This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.

The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This response should be used for temporary conditions and the Retry-After HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.

This error response is given when the server is acting as a gateway and cannot get a response in time.

The HTTP version used in the request is not supported by the server.

The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.

The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.

The server detected an infinite loop while processing the request.

Further extensions to the request are required for the server to fulfill it.

Indicates that the client needs to authenticate to gain network access.

Источник

HTTP Status Codes

Last Updated : December 17, 2021

REST APIs use the Status-Line part of an HTTP response message to inform clients of their request’s overarching result. RFC 2616 defines the Status-Line syntax as shown below:

Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF

HTTP defines these standard status codes that can be used to convey the results of a client’s request. The status codes are divided into five categories.

1xx Status Codes [Informational]

2xx Status Codes [Success]

3xx Status Codes [Redirection]

4xx Status Codes (Client Error)

5xx Status Codes (Server Error)

6. REST Specific HTTP Status Codes

200 (OK)

It indicates that the REST API successfully carried out whatever action the client requested and that no more specific code in the 2xx series is appropriate.

Unlike the 204 status code, a 200 response should include a response body. The information returned with the response is dependent on the method used in the request, for example:

201 (Created)

A REST API responds with the 201 status code whenever a resource is created inside a collection. There may also be times when a new resource is created as a result of some controller action, in which case 201 would also be an appropriate response.

The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field.

The origin server MUST create the resource before returning the 201 status code. If the action cannot be carried out immediately, the server SHOULD respond with a 202 (Accepted) response instead.

202 (Accepted)

A 202 response is typically used for actions that take a long while to process. It indicates that the request has been accepted for processing, but the processing has not been completed. The request might or might not be eventually acted upon, or even maybe disallowed when processing occurs.

Its purpose is to allow a server to accept a request for some other process (perhaps a batch-oriented process that is only run once per day) without requiring that the user agent’s connection to the server persist until the process is completed.

The entity returned with this response SHOULD include an indication of the request’s current status and either a pointer to a status monitor (job queue location) or some estimate of when the user can expect the request to be fulfilled.

204 (No Content)

An API may also send 204 in conjunction with a GET request to indicate that the requested resource exists, but has no state representation to include in the body.

If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent’s active document view. However, any new or updated metainformation SHOULD be applied to the document currently in the user agent’s dynamic view.

The 204 response MUST NOT include a message-body and thus is always terminated by the first empty line after the header fields.

301 (Moved Permanently)

The 301 status code indicates that the REST API’s resource model has been significantly redesigned, and a new permanent URI has been assigned to the client’s requested resource. The REST API should specify the new URI in the response’s Location header, and all future requests should be directed to the given URI.

You will hardly use this response code in your API as you can always use the API versioning for the new API while retaining the old one.

302 (Found)

The HTTP response status code 302 Found is a common way of performing URL redirection. An HTTP response with this status code will additionally provide a URL in the Location header field. The user agent (e.g., a web browser) is invited by a response with this code to make a second. Otherwise identical, request to the new URL specified in the location field.

Many web browsers implemented this code in a manner that violated this standard, changing the request type of the new request to GET, regardless of the type employed in the original request (e.g., POST). RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.

303 (See Other)

A 303 response indicates that a controller resource has finished its work, but instead of sending a potentially unwanted response body, it sends the client the URI of a response resource. The response can be the URI of the temporary status message, or the URI to some already existing, more permanent, resource.

Generally speaking, the 303 status code allows a REST API to send a reference to a resource without forcing the client to download its state. Instead, the client may send a GET request to the value of the Location header.

The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.

304 (Not Modified)

This status code is similar to 204 (“No Content”) in that the response body must be empty. The critical distinction is that 204 is used when there is nothing to send in the body, whereas 304 is used when the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match.

In such a case, there is no need to retransmit the resource since the client still has a previously-downloaded copy.

Using this saves bandwidth and reprocessing on both the server and client, as only the header data must be sent and received in comparison to the entirety of the page being re-processed by the server, then sent again using more bandwidth of the server and client.

307 (Temporary Redirect)

A 307 response indicates that the REST API is not going to process the client’s request. Instead, the client should resubmit the request to the URI specified by the response message’s Location header. However, future requests should still use the original URI.

A REST API can use this status code to assign a temporary URI to the client’s requested resource. For example, a 307 response can be used to shift a client request over to another host.

400 (Bad Request)

400 is the generic client-side error status, used when no other 4xx error code is appropriate. Errors can be like malformed request syntax, invalid request message parameters, or deceptive request routing etc.

The client SHOULD NOT repeat the request without modifications.

401 (Unauthorized)

A 401 error response indicates that the client tried to operate on a protected resource without providing the proper authorization. It may have provided the wrong credentials or none at all. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource.

The client MAY repeat the request with a suitable Authorization header field. If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information.

403 (Forbidden)

A 403 error response indicates that the client’s request is formed correctly, but the REST API refuses to honor it, i.e., the user does not have the necessary permissions for the resource. A 403 response is not a case of insufficient client credentials; that would be 401 (“Unauthorized”).

Authentication will not help, and the request SHOULD NOT be repeated. Unlike a 401 Unauthorized response, authenticating will make no difference.

404 (Not Found)

The 404 error status code indicates that the REST API can’t map the client’s URI to a resource but may be available in the future. Subsequent requests by the client are permissible.

No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.

405 (Method Not Allowed)

The API responds with a 405 error to indicate that the client tried to use an HTTP method that the resource does not allow. For instance, a read-only resource could support only GET and HEAD, while a controller resource might allow GET and POST, but not PUT or DELETE.

A 405 response must include the Allow header, which lists the HTTP methods that the resource supports. For example:

406 (Not Acceptable)

If the response could be unacceptable, a user agent SHOULD temporarily stop receipt of more data and query the user for a decision on further actions.

412 (Precondition Failed)

The 412 error response indicates that the client specified one or more preconditions in its request headers, effectively telling the REST API to carry out its request only if certain conditions were met. A 412 response indicates that those conditions were not met, so instead of carrying out the request, the API sends this status code.

415 (Unsupported Media Type)

For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.

500 (Internal Server Error)

500 is the generic REST API error response. Most web frameworks automatically respond with this response status code whenever they execute some request handler code that raises an exception.

A 500 error is never the client’s fault, and therefore, it is reasonable for the client to retry the same request that triggered this response and hope to get a different response.

The API response is the generic error message, given when an unexpected condition was encountered and no more specific message is suitable.

Источник

HTTP status code for update and delete?

What status code should I set for UPDATE ( PUT ) and DELETE (e.g. product successfully updated)?

10 Answers 10

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

For a PUT request: HTTP 200, HTTP 204 should imply «resource updated successfully». HTTP 201 if the PUT request created a new resource.

For a DELETE request: HTTP 200 or HTTP 204 should imply «resource deleted successfully».

HTTP 202 can also be returned by either operation and would imply that the instruction was accepted by the server, but not fully applied yet. It’s possible that the operation fails later, so the client shouldn’t fully assume that it was success.

A client that receives a status code it doesn’t recognize, but it’s starting with 2 should treat it as a 200 OK.

If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request.

A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.

HTTP 200 OK: Standard response for successful HTTP requests. The actual response will depend on the request method used.

HTTP 204 No Content: The server successfully processed the request, but is not returning any content

Short answer: for both PUT and DELETE, you should send either 200 (OK) or 204 (No Content).

Long answer: here’s a complete decision diagram (click to magnify).

Http code 204. Смотреть фото Http code 204. Смотреть картинку Http code 204. Картинка про Http code 204. Фото Http code 204

Here are some Tips:

DELETE

200 (if you want send some additional data in the Response) or 204 (recommended).

202 Operation deleted has not been committed yet.

If there’s nothing to delete, use 204 or 404 (DELETE operation is idempotent, delete an already deleted item is operation successful, so you can return 204, but it’s true that idempotent doesn’t necessarily imply the same response)

If you’re updating an element of a collection

The referenced element doesn’t exists:

PUT can be 201 (if you created the element because that is your behaviour)

404 If you don’t want to create elements via PUT.

400 Bad Request (Malformed syntax or a bad query more common than in case of DELETE).

401 Unauthorized

403 Forbidden: Authentication failure or invalid Application ID.

405 Not Allowed. Sure.

409 Resource Conflict can be possible in complex systems, as in DELETE.

422 Unprocessable entity It helps to distinguish between a «Bad request» (e.g. malformed XML/JSON) and invalid field values

And 501, 502 in case of errors.

Http code 204. Смотреть фото Http code 204. Смотреть картинку Http code 204. Картинка про Http code 204. Фото Http code 204

And no, it’s not always 200.

Here’s some status code, which you should know for your kind of knowledge.

1XX Information Responses

2XX Success

3XX Redirection

4XX Client errors

5XX Server errors

Источник

Коды ответов REST API

REST API использует строку состояния в HTTP ответе (статус ответа), чтобы информировать Клиентов о результате запроса.

Вообще HTTP определяет 40 стандартных кодов состояния (статусов ответа), которые делятся на пять категорий. Ниже выделены только те коды состояния, которые часто используются в REST API.

КатегорияОписание
1xx: ИнформацияВ этот класс содержит заголовки информирующие о процессе передачи. Это обычно предварительный ответ, состоящий только из Status-Line и опциональных заголовков, и завершается пустой строкой. Нет обязательных заголовков. Серверы НЕ ДОЛЖНЫ посылать 1xx ответы HTTP/1.0 клиентам.
2xx: УспехЭтот класс кодов состояния указывает, что запрос клиента был успешно получен, понят, и принят.
3xx: ПеренаправлениеКоды этого класса сообщают клиенту, что для успешного выполнения операции необходимо сделать другой запрос, как правило, по другому URI. Из данного класса пять кодов 301, 302, 303, 305 и 307 относятся непосредственно к перенаправлениям.
4xx: Ошибка клиентаКласс кодов 4xx предназначен для указания ошибок со стороны клиента.
5xx: Ошибка сервераКоды ответов, начинающиеся с «5» указывают на случаи, когда сервер знает, что произошла ошибка или он не может обработать запрос.

Коды состояний в REST

200 * (OK)

Запрос выполнен успешно. Информация, возвращаемая с ответом зависит от метода, используемого в запросе, например при:

REST API отвечает кодом состояния 201 при каждом создании ресурса в коллекции. Также могут быть случаи, когда новый ресурс создается в результате какого-либо действия контроллера, и в этом случае 201 также будет подходящем ответом.

Ссылка (URL) на новый ресурс может быть в теле ответа или в поле заголовка ответа Location.

Сервер должен создать ресурс перед тем как вернуть 201 статус. Если это невозможно сделать сразу, тогда сервер должен ответить кодом 202 (Accepted).

Ответ 202 обычно используется для действий, которые занимают много времени для обработки и не могут быть выполнены сразу. Это означает, что запрос принят к обработке, но обработка не завершена.

Его цель состоит в том, чтобы позволить серверу принять запрос на какой-либо другой процесс (возможно, пакетный процесс, который выполняется только один раз в день), не требуя, чтобы соединение агента пользователя с сервером сохранялось до тех пор, пока процесс не будет завершен.

Сущность, возвращаемая с этим ответом, должна содержать указание на текущее состояние запроса и указатель на монитор состояния (расположение очереди заданий) или некоторую оценку того, когда пользователь может ожидать выполнения запроса.

Предоставленная информация взята не из оригинального источника (а, например, из кэша, который мог устареть, или из резервной копии, которая могла потерять актуальность). Этот факт отражен в заголовке ответа и подтверждается этим кодом. Предоставленная информация может совпадать, а может и не совпадать с оригинальными данными.

Код состояния 204 обычно отправляется в ответ на запрос PUT, POST или DELETE, когда REST API отказывается отправлять обратно любое сообщение о состоянии проделанной работы.

API может также отправить 204 статус в ответ на GET запрос, чтобы указать, что запрошенный ресурс существует, но не имеет данных для добавления их в тело ответа.

Ответ 204 не должен содержать тело сообщения и, таким образом, всегда завершается первой пустой строкой после полей заголовка.

Сервер успешно обработал запрос и обязывает клиента сбросить введенные пользователем данные. В ответе не должно передаваться никаких данных (в теле ответа). Обычно применяется для возврата в начальное состояние формы ввода данных на клиенте.

Сервер выполнил часть GET запроса ресурса. Запрос ДОЛЖЕН был содержать поле заголовка Range (секция 14.35), который указывает на желаемый диапазон и МОГ содержать поле заголовка If-Range (секция 14.27), который делает запрос условным.

Запрос ДОЛЖЕН содержать следующие поля заголовка:

Кэш НЕ ДОЛЖЕН объединять ответ 206 с другими ранее закэшированными данными, если поле ETag или Last-Modified в точности не совпадают (подробнее в секции 16.5.4)

Кэш, который не поддерживает заголовки Range и Content-Range НЕ ДОЛЖЕН кэшировать ответы 206 (Partial).

По указанному URI существует несколько вариантов предоставления ресурса по типу MIME, по языку или по другим характеристикам. Сервер передаёт с сообщением список альтернатив, давая возможность сделать выбор клиенту автоматически или пользователю.

Если это не запрос HEAD, ответ ДОЛЖЕН включать объект, содержащий список характеристик и адресов, из которого пользователь или агент пользователя может выбрать один наиболее подходящий. Формат объекта определяется по типу данных приведённых в Content-Type поля заголовка. В зависимости от формата и возможностей агента пользователя, выбор наиболее подходящего варианта может выполняться автоматически. Однако эта спецификация не определяет никакого стандарта для автоматического выбора.

Если у сервера есть предпочтительный выбор представления, он ДОЛЖЕН включить конкретный URI для этого представления в поле Location; агент пользователя МОЖЕТ использовать заголовок Location для автоматического перенаправления к предложенному ресурсу. Этот запрос может быть закэширован, если явно не было указано иного.

Вы вряд ли будете использовать этот код ответа в своем API, так как вы всегда можете использовать версию API для нового API, сохраняя при этом старый.

Является распространенным способом выполнить перенаправление на другой URL. HTTP-ответ с этим кодом должен дополнительно предоставит URL-адрес куда перенаправлять в поле заголовка Location. Агенту пользователя (например, браузеру) предлагается в ответе с этим кодом сделать второй запрос на новый URL.

Многие браузеры реализовали этот код таким образом, что нарушили стандарт. Они начали изменять Тип исходного запроса, например с POST на GET. Коды состояния 303 и 307 были добавлены для серверов, которые хотят однозначно определить, какая реакция ожидается от клиента.

Ответ 303 указывает, что ресурс контроллера завершил свою работу, но вместо отправки нежелательного тела ответа он отправляет клиенту URI ресурса. Это может быть URI временного сообщения о состоянии ресурса или URI для уже существующего постоянного ресурса.

Ответ 303 не должен кэшироваться, но ответ на второй (перенаправленный) запрос может быть кэшируемым.

В таком случае нет необходимости повторно передавать ресурс, так как у клиента все еще есть ранее загруженная копия.

Все это экономит ресурсы клиента и сервера, так как только заголовки должны быть отправлены и приняты, и серверу нет необходимости генерировать контент снова, а клиенту его получать.

Доступ к запрошенному ресурсу ДОЛЖЕН быть осуществлен через прокси-сервер, указанный в поле Location. Поле Location предоставляет URI прокси. Ожидается, что получатель повторит этот запрос с помощью прокси. Ответ 305 может генерироваться ТОЛЬКО серверами-источниками.

Заметьте: в спецификации RFC 2068 однозначно не сказано, что ответ 305 предназначен для перенаправления единственного запроса, и что он должен генерироваться только сервером-источником. Упущение этих ограничений вызвало ряд значительных последствий для безопасности.

Многие HTTP клиенты (такие, как Mozilla и Internet Explorer) обрабатывают этот статус некорректно прежде всего из соображений безопасности.

Rest API может использовать этот код состояния для назначения временного URL запрашиваемому ресурсу.

Если метод запроса не HEAD, тело ответа должно содержать короткую заметку с гиперссылкой на новый URL. Если код 307 был получен в ответ на запрос, отличный от GET или HEAD, Клиент не должен автоматически перенаправлять запрос, если он не может быть подтвержден Клиентом, так как это может изменить условия, при которых был создан запрос.

Нужно повторить запрос на другой адрес без изменения применяемого метода.

Этот и все последующие запросы нужно повторить на другой URI. 307 и 308 (как предложено) Схож в поведении с 302 и 301, но не требуют замены HTTP метода. Таким образом, например, отправку формы на «постоянно перенаправленный» ресурс можно продолжать без проблем.

Это общий статус ошибки на стороне Клиента. Используется, когда никакой другой код ошибки 4xx не уместен. Ошибки могут быть как неправильный синтаксис запроса, неверные параметры запроса, запросы вводящие в заблуждение или маршрутизатор и т.д.

Клиент не должен повторять точно такой же запрос.

Клиент может повторить запрос указав в заголовке подходящее поле авторизации. Если это уже было сделано, то в ответе 401 будет указано, что авторизация для указанных учетных данных не работает. Если в ответе 401 содержится та же проблема, что и в предыдущем ответе, и Клиент уже предпринял хотя бы одну попытку проверки подлинности, то пользователю Клиента следует представить данные полученные в ответе, владельцу сайта, так как они могут помочь в диагностике проблемы.

Этот код зарезервирован для использования в будущем.

Предполагается использовать в будущем. В настоящий момент не используется. Этот код предусмотрен для платных пользовательских сервисов, а не для хостинговых компаний. Имеется в виду, что эта ошибка не будет выдана хостинговым провайдером в случае просроченной оплаты его услуг. Зарезервирован, начиная с HTTP/1.1.

Ошибка 403 указывает, что rest API отказывается выполнять запрос клиента, т.е. Клиент не имеет необходимых разрешений для доступа. Ответ 403 не является случаем, когда нужна авторизация (для ошибки авторизации используется код 401).

Попытка аутентификация не поможет, и повторные запросы не имеют смысла.

Указывает, что rest API не может сопоставить URL клиента с ресурсом, но этот URL может быть доступен в будущем. Последующие запросы клиента допустимы.

API выдает ошибку 405, когда клиент пытался использовать HTTP метод, который недопустим для ресурса. Например, указан метод PUT, но такого метода у ресурса нет.

В таких случаях Клиент должен решить проблему данных у себя и только потом отправлять запросы повторно.

Ответ аналогичен коду 401, за исключением того, что аутентификация производится для прокси-сервера. Механизм аналогичен идентификации на исходном сервере.

Пользователь должен сначала авторизоваться через прокси. Прокси-сервер должен вернуть Proxy-Authenticate заголовок, содержащий запрос ресурса. Клиент может повторить запрос вместе с Proxy-Authenticate заголовком. Появился в HTTP/1.1.

Время ожидания сервером передачи от клиента истекло. Клиент не предоставил запрос за то время, пока сервер был готов его принят. Клиент МОЖЕТ повторить запрос без изменений в любое время.

Например, такая ситуация может возникнуть при загрузке на сервер объёмного файла методом POST или PUT. В какой-то момент передачи источник данных перестал отвечать, например, из-за повреждения компакт-диска или потери связи с другим компьютером в локальной сети. Пока клиент ничего не передаёт, ожидая от него ответа, соединение с сервером держится. Через некоторое время сервер может закрыть соединение со своей стороны, чтобы дать возможность другим клиентам сделать запрос.

Запрос нельзя обработать из-за конфликта в текущем состоянии ресурса. Этот код разрешается использовать только в тех случаях, когда ожидается, что пользователь может самостоятельно разрешить этот конфликт и повторить запрос. В тело ответа СЛЕДУЕТ включить достаточное количество информации для того, чтобы пользователь смог понять причину конфликта. В идеале ответ должен содержать такую информацию, которая поможет пользователю или его агенту исправить проблему. Однако это не всегда возможно и это не обязательно.

Как правило, конфликты происходят во время PUT-запроса. Например, во время использования версионирования, если сущность, к которой обращаются методом PUT, содержит изменения, конфликтующие с теми, что были сделаны ранее третьей стороной, серверу следует использовать ответ 409, чтобы дать понять пользователю, что этот запрос нельзя завершить. В этом случае в ответной сущности должен содержаться список изменений между двумя версиями в формате, который указан в поле заголовка Content-Type.

Когда клиент указывает rest API выполнять запрос только при выполнении определенных условий, а API не может выполнить запрос при таких условиях, то возвращается ответ 412.

Такой ответ сервер посылает, если ресурс раньше был по указанному URL, но был удалён и теперь недоступен. Серверу в этом случае неизвестно и местоположение альтернативного документа, например, копии. Если у сервера есть подозрение, что документ в ближайшее время может быть восстановлен, то лучше клиенту передать код 404. Появился в HTTP/1.1.

Для указанного ресурса клиент должен указать Content-Length в заголовке запроса. Без указания этого поля не стоит делать повторную попытку запроса к серверу по данному URI. Такой ответ естественен для запросов типа POST и PUT. Например, если по указанному URI производится загрузка файлов, а на сервере стоит ограничение на их объём. Тогда разумней будет проверить в самом начале заголовок Content-Length и сразу отказать в загрузке, чем провоцировать бессмысленную нагрузку, разрывая соединение, когда клиент действительно пришлёт слишком объёмное сообщение.

Возвращается, если ни одно из условных полей заголовка запроса не было выполнено.

Этот код ответа позволяет клиенту записывать предварительные условия в метаинформации текущего ресурса, таким образом, предотвращая применение запрошенного метода к ресурсу, кроме того, что ожидается.

Возвращается в случае, если сервер отказывается обработать запрос по причине слишком большого размера тела запроса. Сервер может закрыть соединение, чтобы прекратить дальнейшую передачу запроса.

Если проблема временная, то рекомендуется в ответ сервера включить заголовок Retry-After с указанием времени, по истечении которого можно повторить аналогичный запрос.

Сервер не может обработать запрос из-за слишком длинного указанного URL. Эту редкую ошибку можно спровоцировать, например, когда клиент пытается передать длинные параметры через метод GET, а не POST, когда клиент попадает в «чёрную дыру» перенаправлений (например, когда префикс URI указывает на своё же окончание), или когда сервер подвергается атаке со стороны клиента, который пытается использовать дыры в безопасности, которые встречаются на серверах с фиксированной длиной буфера для чтения или обработки Request-URI.

Код состояния 428 указывает, что исходный сервер требует, чтобы запрос был условным.

Его типичное использование — избежать проблемы «потерянного обновления», когда клиент ПОЛУЧАЕТ состояние ресурса, изменяет его и ОТПРАВЛЯЕТ обратно на сервер, когда тем временем третья сторона изменила состояние на сервере, что привело к конфликту. Требуя, чтобы запросы были условными, сервер может гарантировать, что клиенты работают с правильными копиями.

Ответы с этим кодом состояния ДОЛЖНЫ объяснять, как повторно отправить запрос.

Пользователь отправил слишком много запросов за заданный промежуток времени.

Представления ответа ДОЛЖНЫ включать подробности, объясняющие условие, и МОГУТ включать заголовок Retry-After, указывающий, как долго ждать, прежде чем делать новый запрос.

Код состояния 431 указывает на то, что сервер не желает обрабатывать запрос, поскольку его поля заголовка слишком велики. Запрос МОЖЕТ быть отправлен повторно после уменьшения размера полей заголовка запроса.

Его можно использовать как в случае, когда совокупность полей заголовка запроса слишком велика, так и в случае неисправности одного поля заголовка. В последнем случае представление ответа ДОЛЖНО указывать, какое поле заголовка было слишком большим.

Код ответа Nginx. Сервер не вернул информацию и закрыл соединение. (полезно в качестве сдерживающего фактора для вредоносных программ)

Доступ к ресурсу закрыт по юридическим причинам. Наиболее близким из существующих является код 403 Forbidden (сервер понял запрос, но отказывается его обработать). Однако в случае цензуры, особенно когда это требование к провайдерам заблокировать доступ к сайту, сервер никак не мог понять запроса — он его даже не получил. Совершенно точно подходит другой код: 305 Use Proxy. Однако такое использование этого кода может не понравиться цензорам. Было предложено несколько вариантов для нового кода, включая «112 Emergency. Censorship in action» и «460 Blocked by Repressive Regime»

Общий ответ при ошибке в коде. Универсальное сообщение о внутренней ошибке сервера, когда никакое более определенное сообщение не подходит.

Большинство веб-платформ автоматически отвечают этим кодом состояния, когда при выполнении кода обработчика запроса возникла ошибка.

Ошибка 500 никогда не зависит от клиента, поэтому для клиента разумно повторить точно такой же запрос, и надеяться что в этот раз сервер отработает без ошибок.

Серверу либо неизвестен метод запроса, или ему (серверу) не хватает возможностей выполнить запрос. Обычно это подразумевает будущую доступность (например, новая функция API веб-сервиса).

Если же метод серверу известен, но он не применим к данному ресурсу, то нужно вернуть ответ 405.

Сервер, выступая в роли шлюза или прокси-сервера, получил некорректный ответ от вышестоящего сервера, к которому он обратился. Появился в HTTP/1.0.

Сервер не может обработать запрос из-за временной перегрузки или технических работ. Это временное состояние, из которого сервер выйдет через какое-то время. Если это время известно, то его МОЖНО передать в заголовке Retry-After.

Сервер, в роли шлюза или прокси-сервера, не дождался в рамках установленного таймаута ответа от вышестоящего сервера текущего запроса.

Сервер не поддерживает или отказывается поддерживать указанную в запросе версию протокола HTTP.

В запросе не соблюдена политика доступа к ресурсу. Сервер должен отправить обратно всю информацию, необходимую клиенту для отправки расширенного запроса. Указание того, как расширения информируют клиента, выходит за рамки данной спецификации.

Источник

Коды статусов ответа по протоколу HTTP

Информационный (Informational 1xx)

100=»Continue»
Начальная часть запроса принята, и клиент может продолжать передачу запроса.
101=»Switching Protocols»
Сервер выполняет требование клиента и переключает протоколы в соответствии с указанием, данным в поле заголовка Upgrade.

Запрос клиента успешен (Successful 2xx)

Ответы в диапазоне 200-299 означают, что запрос клиента обработан успешно.

200=»OK»
Запрос клиента обработан успешно, и ответ сервера содержит затребованные данные.
201=»Created»
Этот код состояния используется в случае создания нового URI. Вместе с этим кодом результата сервер выдает заголовок Location (см. главу 19), который содержит информацию о том, куда были помещены новые данные.
202=»Accepted»
Запрос принят, но обрабатывается не сразу. В теле содержимого ответа сервера может быть дана дополнительная информация о данной транзакции. Гарантии того, что сервер в конечном итоге удовлетворит запрос, нет, даже несмотря на то, что на момент приема запрос выглядел допустимым.
203=»Non-Authoritative Information»
Информация в заголовке содержимого взята из локальной копии или у третьей стороны, а не с исходного сервера.
204=»No Content»
Ответ содержит код состояния и заголовок, но тело содержимого отсутствует. При получении этого ответа броузер не должен обновлять свой документ. Обработчик чувствительных областей изображений может возвращать этот код, когда пользователь щелкает на бесполезных или пустых участках изображения.
205=»Reset Content»

Броузер должен очистить форму, используемую в данной транзакции, для дополнительных входных данных. Полезен для CGI-приложений, требующих ввода данных.

Сервер возвращает лишь часть данных затребованного объема. Используется в ответе на запрос с указанием заголовка Range. Сервер должен указать диапазон, включенный в ответ, в заголовке Content-Range.

Запрос клиента переадресован (Redirection 3xx)

Код ответа в диапазоне 300-399 означает, что запрос не выполнен и клиенту нужно предпринять некоторые действия для удовлетворения запроса.

Это код ответа на заголовок lf-Modified-Since, если URI не изменялся с указанной даты. Тело содержимого не посылается, и клиент должен использовать свою локальную копию.

Доступ к затребованному URI должен осуществляться через proxy-сервер, указанный в заголовке Location.

Запрос клиента является неполным (Client Error 4xx)

Коды ответов в диапазоне 400-499 означают, что запрос клиента неполный. Эти коды могут также означать, что от клиента требуется дополнительная информация.

Сервер не будет обрабатывать запрос, потому что его тело имеет неподдерживаемый формат.

416=»Requested Range Not Satisfiable»

Запрашиваемый диапазон не допустим

Ожидание не удалось

Превышен лимит запросов

450=Rating Service Unavailable

451=Unavailable For Legal Reasons

452 could be site not permitted by employer,

453 could be site not permitted by ISP

460 Blocked by Repressive Regime

Ошибки сервера (Server Error 5xx)

Коды ответов в диапазоне 500-599 показывают, что сервер столкнулся с ошибкой и, вероятно, не сможет выполнить запрос клиента.

Сервер не поддерживает версию протокола HTTP, использованную в запросе.

Ошибки ( Error 7xx)

Ошибки ( Error 9xx)

Для отправки кода статуса из PHP используется директива «header Status».

Источник

HTTP Get with 204 No Content: Is that normal

Part of Google Cloud Collective

The use case for this question is a Java application that I am writing for Google App Engine. I am sending a request to a servlet, but the data to be sent back to the client will be transmitted through a Channel API socket instead of in the HTTP Response. Currently, my client sends a POST with no content in the request body and waits for a 204 response back from the servlet before polling the Channel API socket. Because no data I being sent in the body of the request, I am debating whether it makes more sense for me to send a GET instead of a POST.

Http code 204. Смотреть фото Http code 204. Смотреть картинку Http code 204. Картинка про Http code 204. Фото Http code 204

5 Answers 5

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

I use GET/204 with a RESTful collection that is a positional array of known fixed length but with holes.

Источник

HTTP Status 204 (No Content)

Last Updated : September 28, 2021

HTTP Status 204 (No Content) indicates that the server has successfully fulfilled the request and that there is no content to send in the response payload body.

The server might want to return updated meta-information in the form of entity headers, which, if present, SHOULD be applied to the current document’s active view if any.

The 204 response MUST NOT include a message-body and thus is always terminated by the first empty line after the header fields.

1. Cacheable

By default, 204 (No Content) the response is cacheable. If caching needs to be overridden then the response must include cache respective cache headers.

For example, you may want to return status 204 (No Content) in UPDATE operations where request payload is large enough not to transport back and forth. The user agent will send the payload to the server to update the resource.

If the operation is successful, the server will respond with 204 to indicate the success so that client application can update its UI to inform the user about the operation’s success.

It is also frequently used with interfaces that expect automated data transfers to be prevalent, such as within distributed version control systems.

2. Resolving lost update problem

With status 204, the server may also include an HTTP header ETag to let the client validate client-side resource representation before making a further update on the server – to avoid the lost update problem.

Lost update problem happens when multiple people edit a resource without knowledge of each other’s changes.

In this scenario, the last person to update a resource “wins,” and previous updates are lost.

ETags can be used in combination with the If-Match header to let the server decide if a resource should be updated. If ETag does not match then the server informs the client via a 412 (Precondition Failed) response.

Источник

Http code 204

Each Status-Code is described below, including a description of which method(s) it can follow and any metainformation required in the response.

10.1 Informational 1xx

This class of status code indicates a provisional response, consisting only of the Status-Line and optional headers, and is terminated by an empty line. There are no required headers for this class of status code. Since HTTP/1.0 did not define any 1xx status codes, servers MUST NOT send a 1xx response to an HTTP/1.0 client except under experimental conditions.

A client MUST be prepared to accept one or more 1xx status responses prior to a regular response, even if the client does not expect a 100 (Continue) status message. Unexpected 1xx status responses MAY be ignored by a user agent.

Proxies MUST forward 1xx responses, unless the connection between the proxy and its client has been closed, or unless the proxy itself requested the generation of the 1xx response. (For example, if a

proxy adds a «Expect: 100-continue» field when it forwards a request, then it need not forward the corresponding 100 (Continue) response(s).)

10.1.1 100 Continue

The client SHOULD continue with its request. This interim response is used to inform the client that the initial part of the request has been received and has not yet been rejected by the server. The client SHOULD continue by sending the remainder of the request or, if the request has already been completed, ignore this response. The server MUST send a final response after the request has been completed. See section 8.2.3 for detailed discussion of the use and handling of this status code.

10.1.2 101 Switching Protocols

The server understands and is willing to comply with the client’s request, via the Upgrade message header field (section 14.42), for a change in the application protocol being used on this connection. The server will switch protocols to those defined by the response’s Upgrade header field immediately after the empty line which terminates the 101 response.

The protocol SHOULD be switched only when it is advantageous to do so. For example, switching to a newer version of HTTP is advantageous over older versions, and switching to a real-time, synchronous protocol might be advantageous when delivering resources that use such features.

10.2 Successful 2xx

This class of status code indicates that the client’s request was successfully received, understood, and accepted.

10.2.1 200 OK

The request has succeeded. The information returned with the response is dependent on the method used in the request, for example:

GET an entity corresponding to the requested resource is sent in the response;

HEAD the entity-header fields corresponding to the requested resource are sent in the response without any message-body;

POST an entity describing or containing the result of the action;

TRACE an entity containing the request message as received by the end server.

10.2.2 201 Created

The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field. The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. The origin server MUST create the resource before returning the 201 status code. If the action cannot be carried out immediately, the server SHOULD respond with 202 (Accepted) response instead.

A 201 response MAY contain an ETag response header field indicating the current value of the entity tag for the requested variant just created, see section 14.19.

10.2.3 202 Accepted

The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. There is no facility for re-sending a status code from an asynchronous operation such as this.

The 202 response is intentionally non-committal. Its purpose is to allow a server to accept a request for some other process (perhaps a batch-oriented process that is only run once per day) without requiring that the user agent’s connection to the server persist until the process is completed. The entity returned with this response SHOULD include an indication of the request’s current status and either a pointer to a status monitor or some estimate of when the user can expect the request to be fulfilled.

10.2.4 203 Non-Authoritative Information

The returned metainformation in the entity-header is not the definitive set as available from the origin server, but is gathered from a local or a third-party copy. The set presented MAY be a subset or superset of the original version. For example, including local annotation information about the resource might result in a superset of the metainformation known by the origin server. Use of this response code is not required and is only appropriate when the response would otherwise be 200 (OK).

10.2.5 204 No Content

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent’s active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent’s active view.

The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.

10.2.6 205 Reset Content

The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent. This response is primarily intended to allow input for actions to take place via user input, followed by a clearing of the form in which the input is given so that the user can easily initiate another input action. The response MUST NOT include an entity.

10.2.7 206 Partial Content

The server has fulfilled the partial GET request for the resource. The request MUST have included a Range header field (section 14.35) indicating the desired range, and MAY have included an If-Range header field (section 14.27) to make the request conditional.

The response MUST include the following header fields:

If the 206 response is the result of an If-Range request that used a strong cache validator (see section 13.3.3), the response SHOULD NOT include other entity-headers. If the response is the result of an If-Range request that used a weak validator, the response MUST NOT include other entity-headers; this prevents inconsistencies between cached entity-bodies and updated headers. Otherwise, the response MUST include all of the entity-headers that would have been returned with a 200 (OK) response to the same request.

A cache MUST NOT combine a 206 response with other previously cached content if the ETag or Last-Modified headers do not match exactly, see 13.5.4.

A cache that does not support the Range and Content-Range headers MUST NOT cache 206 (Partial) responses.

10.3 Redirection 3xx

This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. The action required MAY be carried out by the user agent without interaction with the user if and only if the method used in the second request is GET or HEAD. A client SHOULD detect infinite redirection loops, since such loops generate network traffic for each redirection.

10.3.1 300 Multiple Choices

The requested resource corresponds to any one of a set of representations, each with its own specific location, and agent- driven negotiation information (section 12) is being provided so that the user (or user agent) can select a preferred representation and redirect its request to that location.

Unless it was a HEAD request, the response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content- Type header field. Depending upon the format and the capabilities of

the user agent, selection of the most appropriate choice MAY be performed automatically. However, this specification does not define any standard for such automatic selection.

If the server has a preferred choice of representation, it SHOULD include the specific URI for that representation in the Location field; user agents MAY use the Location field value for automatic redirection. This response is cacheable unless indicated otherwise.

10.3.2 301 Moved Permanently

The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. Clients with link editing capabilities ought to automatically re-link references to the Request-URI to one or more of the new references returned by the server, where possible. This response is cacheable unless indicated otherwise.

The new permanent URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).

If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

10.3.3 302 Found

The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.

The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).

If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

10.3.4 303 See Other

The response to the request can be found under a different URI and SHOULD be retrieved using a GET method on that resource. This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource. The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.

The different URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).

10.3.5 304 Not Modified

If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code. The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.

The response MUST include the following header fields:

If a clockless origin server obeys these rules, and proxies and clients add their own Date to any response received without one (as already specified by [RFC 2068], section 14.19), caches will operate correctly.

If the conditional GET used a strong cache validator (see section 13.3.3), the response SHOULD NOT include other entity-headers. Otherwise (i.e., the conditional GET used a weak validator), the response MUST NOT include other entity-headers; this prevents inconsistencies between cached entity-bodies and updated headers.

If a 304 response indicates an entity not currently cached, then the cache MUST disregard the response and repeat the request without the conditional.

If a cache uses a received 304 response to update a cache entry, the cache MUST update the entry to reflect any new field values given in the response.

10.3.6 305 Use Proxy

The requested resource MUST be accessed through the proxy given by the Location field. The Location field gives the URI of the proxy. The recipient is expected to repeat this single request via the proxy. 305 responses MUST only be generated by origin servers.

10.3.7 306 (Unused)

The 306 status code was used in a previous version of the specification, is no longer used, and the code is reserved.

10.3.8 307 Temporary Redirect

The requested resource resides temporarily under a different URI. Since the redirection MAY be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.

If the 307 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

10.4 Client Error 4xx

The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. User agents SHOULD display any included entity to the user.

If the client is sending data, a server implementation using TCP SHOULD be careful to ensure that the client acknowledges receipt of the packet(s) containing the response, before the server closes the input connection. If the client continues sending data to the server after the close, the server’s TCP stack will send a reset packet to the client, which may erase the client’s unacknowledged input buffers before they can be read and interpreted by the HTTP application.

10.4.1 400 Bad Request

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

10.4.2 401 Unauthorized

The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information. HTTP access authentication is explained in «HTTP Authentication: Basic and Digest Access Authentication» [43].

10.4.3 402 Payment Required

This code is reserved for future use.

10.4.4 403 Forbidden

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

10.4.5 404 Not Found

The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.

10.4.6 405 Method Not Allowed

The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.

10.4.7 406 Not Acceptable

The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.

Unless it was a HEAD request, the response SHOULD include an entity containing a list of available entity characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. Depending upon the format and the capabilities of the user agent, selection of the most appropriate choice MAY be performed automatically. However, this specification does not define any standard for such automatic selection.

If the response could be unacceptable, a user agent SHOULD temporarily stop receipt of more data and query the user for a decision on further actions.

10.4.8 407 Proxy Authentication Required

This code is similar to 401 (Unauthorized), but indicates that the client must first authenticate itself with the proxy. The proxy MUST return a Proxy-Authenticate header field (section 14.33) containing a challenge applicable to the proxy for the requested resource. The client MAY repeat the request with a suitable Proxy-Authorization header field (section 14.34). HTTP access authentication is explained in «HTTP Authentication: Basic and Digest Access Authentication» [43].

10.4.9 408 Request Timeout

The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.

10.4.10 409 Conflict

The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough

information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.

Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can’t complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.

10.4.11 410 Gone

The requested resource is no longer available at the server and no forwarding address is known. This condition is expected to be considered permanent. Clients with link editing capabilities SHOULD delete references to the Request-URI after user approval. If the server does not know, or has no facility to determine, whether or not the condition is permanent, the status code 404 (Not Found) SHOULD be used instead. This response is cacheable unless indicated otherwise.

10.4.12 411 Length Required

The server refuses to accept the request without a defined Content- Length. The client MAY repeat the request if it adds a valid Content-Length header field containing the length of the message-body in the request message.

10.4.13 412 Precondition Failed

The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server. This response code allows the client to place preconditions on the current resource metainformation (header field data) and thus prevent the requested method from being applied to a resource other than the one intended.

10.4.14 413 Request Entity Too Large

The server is refusing to process a request because the request entity is larger than the server is willing or able to process. The server MAY close the connection to prevent the client from continuing the request.

If the condition is temporary, the server SHOULD include a Retry- After header field to indicate that it is temporary and after what time the client MAY try again.

10.4.15 414 Request-URI Too Long

The server is refusing to service the request because the Request-URI is longer than the server is willing to interpret. This rare condition is only likely to occur when a client has improperly converted a POST request to a GET request with long query information, when the client has descended into a URI «black hole» of redirection (e.g., a redirected URI prefix that points to a suffix of itself), or when the server is under attack by a client attempting to exploit security holes present in some servers using fixed-length buffers for reading or manipulating the Request-URI.

10.4.16 415 Unsupported Media Type

The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.

10.4.17 416 Requested Range Not Satisfiable

A server SHOULD return a response with this status code if a request included a Range request-header field (section 14.35), and none of the range-specifier values in this field overlap the current extent of the selected resource, and the request did not include an If-Range request-header field. (For byte-ranges, this means that the first- byte-pos of all of the byte-range-spec values were greater than the current length of the selected resource.)

When this status code is returned for a byte-range request, the response SHOULD include a Content-Range entity-header field specifying the current length of the selected resource (see section 14.16). This response MUST NOT use the multipart/byteranges content- type.

10.4.18 417 Expectation Failed

The expectation given in an Expect request-header field (see section 14.20) could not be met by this server, or, if the server is a proxy, the server has unambiguous evidence that the request could not be met by the next-hop server.

10.5 Server Error 5xx

Response status codes beginning with the digit «5» indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. User agents SHOULD display any included entity to the user. These response codes are applicable to any request method.

10.5.1 500 Internal Server Error

The server encountered an unexpected condition which prevented it from fulfilling the request.

10.5.2 501 Not Implemented

The server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource.

10.5.3 502 Bad Gateway

The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.

10.5.4 503 Service Unavailable

The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. If known, the length of the delay MAY be indicated in a Retry-After header. If no Retry-After is given, the client SHOULD handle the response as it would for a 500 response.

10.5.5 504 Gateway Timeout

The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed to access in attempting to complete the request.

10.5.6 505 HTTP Version Not Supported

The server does not support, or refuses to support, the HTTP protocol version that was used in the request message. The server is indicating that it is unable or unwilling to complete the request using the same major version as the client, as described in section 3.1, other than with this error message. The response SHOULD contain an entity describing why that version is not supported and what other protocols are supported by that server.

Источник

10 Описания кодов состояния (Status Code Definitions).

Каждый код состояния, описанный ниже, включает описание метода (или методов), за которым он может следовать и метаинформации, требуемой в ответе.

Этот класс кодов состояния указывает предварительный (временный) ответ, состоящий только из строки состояния (Status-Line) и опциональных заголовков, и завершающийся пустой строкой. Так как HTTP/1.0 не определял никаких 1xx кодов состояния, серверы НЕ ДОЛЖНЫ посылать 1xx ответы HTTP/1.0 клиентам, за исключением экспериментальных условий.

10.1.1 100 Продолжать, Continue.

Клиент может продолжать запрос. Этот промежуточный ответ используется, для того, чтобы сообщить клиенту, что начальная часть запроса была получена и еще не отвергнута сервером. Клиенту СЛЕДУЕТ продолжить посылку оставшихся данных запроса или, если запрос уже был выполнен, игнорировать этот ответ. Сервер ДОЛЖЕН послать заключительный ответ после того, как запрос будет выполнен.

10.1.2 101 Переключение протоколов, Switching Protocols.

Сервер понимает и желает выполнить запрос клиента, если протокол прикладной программы в этом соединении будет изменен на тот, который указан в поле заголовка сообщения Upgrade (раздел 14.41). Сервер переключит протокол на тот, который определен в поле заголовка ответа Upgrade непосредственно после пустой строки, которая завершает ответ с кодом состояния 101.

Протокол должен быть переключен только тогда, когда это принесет выгоду. Например, переключение на более новую версию HTTP выгодно по сравнения с использованием более старых версий, а переключение на синхронный протокол реального времени может быть выгодно при предоставлении ресурсов, которые используют такие возможности.

Этот класс кодов состояния указывает, что запрос клиента был успешно получен, понят, и принят.

10.2.1 200 OK.

Запрос был удачно выполнен. Информация, возвращаемая с ответом зависит от метода, используемого в запросе. Например: GET в ответе представлен объект, соответствующий запрошенному ресурсу; HEAD в ответе представлены поля заголовка объекта (entity-header), соответствующие запрошенному ресурсу. Тело сообщения (message-body) отсутствует; POST в ответе представлено описание объекта или содержится результат действия; TRACE в ответе представлен объект, содержащий сообщение запроса, полученого конечным сервером.

10.2.2 201 Создан, Created.

Запрос был выполнен и в результате был создан новый ресурс. Новый созданный ресурс может быть вызван по URI (одному или нескольким), возвращенным в объекте ответа; наиболее специфический URL для ресурса отдается в поле заголовка Location. Первоначальный сервер ДОЛЖЕН создать ресурс перед возвратом кода состояния 201. Если действие не может быть выполнено немедленно, сервер должен возвратить ответ с кодом состояния 202 (Принято, Accepted) вместо 201.

10.2.3 202 Принято, Accepted.

Запрос был принят для обработки, но обработка не была завершена. В конечном счете запрос МОЖЕТ быть, а МОЖЕТ и не быть выполнен, поскольку он МОЖЕТ быть отвергнут при фактической обработке. Не имеется никакой возможности вторичной посылки кода состояния от асинхронной операции типа этой.

Ответ с кодом состояния 202 преднамеренно уклончив. Цель его состоит в том, чтобы позволить серверу принять запрос для некоторого другого процесса (возможно пакетно-ориентированного процесса, который выполняется только один раз в день) и не требовать при этом, чтобы соединение агента пользователя с сервером сохранялось до завершения процесса. Объекту, возвращенному с этим ответом СЛЕДУЕТ содержать индикатор текущего состояния запроса и либо ссылку на монитор состояния, либо некоторую оценку времени, когда пользователь может ожидать завершения выполнения запроса.

10.2.4 203 Не авторская информация, Non-Authoritative Information.

10.2.5 204 Нет содержимого, No Content.

Ответ с кодом состояния 204 НЕ ДОЛЖЕН содержать тела сообщения, и, таким образом, всегда завершается первой пустой строкой после полей заголовка.

10.2.6 205 Сбросить содержимое, Reset Content.

Сервер выполнил запрос, и агенту пользователя СЛЕДУЕТ отменить просмотр документа, который инициировал запрос. Этот ответ предназначен прежде всего для того, чтобы позволить ввод данных, осуществляемый пользователем, с последующей очисткой формы, в которой сделан ввод, так, чтобы пользователь мог легко инициировать следующее действие ввода. Ответ НЕ ДОЛЖЕН содержать объект.

10.2.7 206 Частичное содержимое, Partial Content.

Сервер выполнил частичный GET запрос ресурса. Запрос должен содержать поле заголовка Range (раздел 14.36), указывающее желаемый диапазон. Ответ ДОЛЖЕН содержать либо поле заголовка Content-Range (раздел 14.17), указывающее диапазон, включенный в ответ, либо тип содержимого (Content-Type) должен быть равным «multipart/byteranges», а поля Content-Range должны содержаться в каждой части. Если «multipart/byteranges» не используется, поле заголовка Content-Length в ответе ДОЛЖНО соответствовать фактическому числу октетов (OCTETs), переданных в теле сообщения (message-body).

Кэш, который не поддерживает заголовки Range и Content-Range НЕ ДОЛЖЕН кэшировать ответы с кодом состояния 206.

Этот класс кодов состояния указывает, что для выполнения запроса агенту пользователя необходимо придпринять дополнительное действие. Требуемое действие МОЖЕТ быть выполнено агентом пользователя без взаимодействия с пользователем, тогда и только тогда, когда во втором запросе используется метод GET или HEAD. Агенту пользователя НЕ СЛЕДУЕТ автоматически перенаправлять запрос более 5 раз, так как такие переадресации обычно указывают бесконечный цикл.

10.3.1 300 Множественный выбор, Multiple Choices.

Запрошенный ресурс имеет несколько представлений, и можно использовать любое из перечисленных. Каждое представление имеет свое расположение и информацию для агента по управлению диалогом (раздел 12), представленную таким образом, что пользователь (или агент пользователя) может выбрать наиболее подходящее представление и перенаправить запрос к нему.

Если запрос был отличен от HEAD, то ответу СЛЕДУЕТ содержать объект, включающий список характеристик и адресов, из которого пользователь или агент пользователя может выбрать один наиболее подходящий. Формат объекта определяется медиа типом, указанным в поле заголовка Content-Type. В зависимости от формата и возможностей агента пользователя, выбор наиболее подходящего представления может выполняться автоматически. Однако, эта спецификация не определяет какого-либо стандарта для автоматического выбора.

Если сервер имеет представление по умолчанию (наиболее предпочтительное), то ему СЛЕДУЕТ включить URL этого представления в поле Location; агенты пользователя МОГУТ использовать значение поля Location для автоматической переадресации. Этот ответ является кэшируемым, если не обозначено иного.

10.3.2 301 Постоянно перенесен, Moved Permanently.

Запрошенному ресурсу был назначен новый постоянный URI, и любые будущие ссылки на этот ресурс СЛЕДУЕТ выполнять, используя один из возвращенных URI. Клиентам с возможностями редактирования связей СЛЕДУЕТ автоматически переопределить ссылки на запрашиваемый URI (Request-URI), используя одну или несколько новых ссылок, возвращенных сервером в тех местах, где это возможно. Этот ответ является кэшируемым, если не обозначено иного.

Если код состояния 301 был получен в ответ на запрос, отличный от GET или HEAD, агент пользователя НЕ ДОЛЖЕН автоматически переназначать запрос, пока нет подтверждения пользователя, так как иначе условия запроса изменятся.

Обратите внимание: При автоматическом переназначении запроса POST после получения кода состояния 301, некоторые существующие HTTP/1.0 агенты пользователя ошибочно изменят метод запроса на GET.

10.3.3 302 Временно перемещен, Moved Temporarily.

Запрошенный ресурс временно находится под другим URI. Так как переадресация может быть изменена в любой момент, клиенту СЛЕДУЕТ продолжать использовать запрашиваемый URI (Request-URI) в будущих запросах. Кэшируемость этого ответа зависит только от содержимого полей заголовка Cache-Control или Expires (если этих полей нет, то ответ не кэшируется).

Если код состояния 302 был получен в ответ на запрос, отличный от GET или HEAD, агент пользователя НЕ ДОЛЖЕН автоматически переназначать запрос, пока нет подтверждения пользователя, так как иначе условия запроса изменятся.

Обратите внимание: При автоматическом переназначении запроса POST после получения кода состояния 302, некоторые существующие HTTP/1.0 агенты пользователя ошибочно изменят метод запроса на GET.

10.3.4 303 Смотреть другой, See Other.

10.3.5 304 Не модифицирован, Not Modified.

Если клиент выполнил условный GET запрос, и доступ разрешен, но документ не изменился, то серверу СЛЕДУЕТ ответить, используя этот код состояния. Ответ НЕ ДОЛЖЕН содержать тела сообщения.

Если условный GET использует строгое сравнение кэша (strong cache validator) (смотреть раздел 13.3.3), ответу НЕ СЛЕДУЕТ содержать других заголовков объекта (entity-headers). Иначе (то есть, если условный GET использует слабое сравнение (weak validator)), ответ НЕ ДОЛЖЕН содержать других заголовков объекта; это предотвращает несогласованности между кэшированными телами объектов (entity-bodies) и модифицированными заголовками.

Если ответ с кодом состояния 304 указывает объект, в настоящее время не кэшированный, то кэш ДОЛЖЕН игнорировать ответ и повторить запрос без условного выражения.

Если кэш использует полученный ответ с кодом состояния 304 для модифицикации вхождения кэша, кэш ДОЛЖЕН модифицировать вхождение так, чтобы отразить любые новые значения полей, данные в ответе.

Ответ с кодом состояния 304 НЕ ДОЛЖЕН включать тела сообщения (message-body), и, таким образом, всегда завершается первой пустой строкой после полей заголовка.

10.3.6 305 Используйте прокси-сервер, Use Proxy.

Обращение к запрошенному ресурсу ДОЛЖНО производиться через прокси-сервер, указанный в поле Location. В поле Location указан URL прокси-сервера. Ожидается, что получатель повторит запрос через прокси-сервер.

Класс кодов состояния 4xx предназначен для случаев, когда клиент, возможно, допустил ошибку. За исключением ответа на запрос HEAD, серверу СЛЕДУЕТ включить объект, содержащий объяснение ошибочной ситуации, и объяснение, является ли она временной или постоянной. Эти коды состояния применимы к любому методу запроса. Агентам пользователя СЛЕДУЕТ показывать пользователю любой включенный объект.

Обратите внимание: Если клиент посылает данные, то реализации сервера, использующей TCP, следует гарантировать, что клиент подтвердил получение пакета(ов), содержащего ответ, прежде чем сервер закроет соединение. Если клиент продолжает посылать данные серверу после закрытия соединения, TCP стек сервера пошлет пакет сброса (RST) клиенту, а TCP стек клиента, в свою очередь, может стереть клиентские неподтвержденные входные буфера прежде, чем они будут прочитаны и интерпретированы приложением HTTP.

10.4.1 400 Испорченный Запрос, Bad Request.

Запрос не может быть понят сервером из-за malformed синтаксиса. Клиенту НЕ СЛЕДУЕТ повторять запрос без модификаций.

10.4.2 401 Несанкционированно, Unauthorized.

Запрос требует установления подлинности пользователя. Ответ ДОЛЖЕН включать поле заголовка WWW-Authenticate (раздел 14.46), содержащее вызов (challenge), применимый к запрошенному ресурсу. Клиент МОЖЕТ повторить запрос с подходящим полем заголовка Authorization (раздел 14.8). Если запрос уже включает рекомендации установления подлинности (Authorization credentials) в поле Authorization, то ответ с кодом состояния 401 указывает, что в установлении подлинности этим рекомендациям отказано. Если ответ с кодом состояния 401 содержит тот же самый вызов, что и предшествующий ответ, а агент пользователя уже делал попытку установления подлинности по крайней мере один раз, то СЛЕДУЕТ показать пользователю объект, который был дан в ответе, так как этот объект МОЖЕТ включать relevant диагностическую информацию. Установление подлинности доступа в протоколе HTTP описывается в разделе 11.

10.4.3 402 Требуется оплата, Payment Required.

Этот код зарезервирован для будущего использования.

10.4.4 403 Запрещено, Forbidden.

Сервер понял запрос, но отказывается выполнять его. Установление подлинности (Authorization) не поможет, и запрос НЕ ДОЛЖЕН быть повторен. Если метод запроса не HEAD и сервер желает указать, почему запрос не был выполнен, ему СЛЕДУЕТ описать причину отказа в объекте. Этот код состояния обычно используется, когда сервер не желает указывать точную причину отказа, или когда никакой другой ответ не подходит.

10.4.5 404 Не найден, Not Found.

Сервер не нашел ничего, соответствующего данному запрашиваемому URI (Request-URI). Никак не сообщается является ли такое положение временным или постоянным.

Если сервер не желает делать данную информацию доступной клиенту, то вместо этого кода состояния может использоваться код состояния 403 (Запрещено, Forbidden). Код состояния 410 (Удален, Gone) СЛЕДУЕТ использовать, если сервер знает через некоторый внутренне конфигурируемый механизм, что старый ресурс более недоступен, но не знает нового адреса для пересылки.

10.4.6 405 Метод не дозволен, Method Not Allowed.

Метод, определенный в строке запроса (Request-Line) не дозволено применять для ресурса, идентифицированного запрашиваемым URI (Request-URI). Ответ ДОЛЖЕН включать заголовок Allow, содержащий список допустимых методов для запрошенного ресурса.

10.4.7 406 Не приемлем, Not Acceptable.

Ресурс, идентифицируемый запросом, имеет возможности генерации только таких объектов ответа, которые имеют характеристики содержимого (content characteristics), не согласующиеся с заголовками приема (accept headers), представленными в запросе.

Если это был не запрос HEAD, то в ответ СЛЕДУЕТ включить объект, содержащий список доступных характеристик объекта и адреса (locations), из которых пользователь или агент пользователя может выбрать наиболее подходящий. Формат объекта определеятся медиа типом, представленным в поле заголовка Content-Type. В зависимости от формата и возможностей агента пользователя, выбор наиболее подходящего варианта может выполняться автоматически. Однако, эта спецификация не определяет никакого стандарта для автоматического выбора.

Обратите внимание: HTTP/1.1 серверы позволяют возвращать ответы, которые не приемлемы согласно заголовкам приема (accept headers), представленным в запросе. В некоторых случаях, это может быть даже предпочтительно по сравнению с посылкой ответа с кодом состояния 406. Агентам пользователя неплохо бы рассматривать заголовки поступившего ответа, чтобы определить, является ли он приемлемым. Если ответ недопустим, агенту пользователя СЛЕДУЕТ временно остановиться, чтобы получить больше данных и спросить пользователя о дальнейших действиях.

10.4.8 407 Требуется установление подлинности через прокси-сервер, Proxy Authentication Required.

Этот код подобен коду 401 (Несанкционированно, Unauthorized), но указывает, что клиент ДОЛЖЕН сначала установить свою подлинность (authenticate) прокси-серверу. Прокси-сервер ДОЛЖЕН возвратить поле заголовка Proxy-Authenticate (раздел 14.33), содержащее вызов (challenge), применяемый прокси-сервером для запрошенного ресурса. Клиент МОЖЕТ повторить запрос с подходящим полем заголовка Proxy-Authorization (раздел 14.34). Установление подлинности доступа в протоколе HTTP описывается в разделе 11.

10.4.9 408 Истекло время ожидания запроса, Request Timeout.

Клиент не произвел запрос в течение времени, которое сервер готов ждать. Клиент МОЖЕТ повторить запрос без модификаций позже.

10.4.10 409 Конфликт, Conflict.

Запрос не был выполнен из-за конфликта с текущим состоянием ресурса. Этот код позволяется только в ситуациях, когда ожидается, что пользователь может решить конфликт и повторно передать запрос. Телу ответа СЛЕДУЕТ содержать достаточное количество информации для пользователя, чтобы он мог распознать источник конфликта. В идеале, объект ответа должен включать достаточно информации для пользователя или агента пользователя для решения проблемы; однако это может не быть возможно, да и не требуется.

Конфликты, наиболее вероятно, будут возникать в ответ на запрос PUT. Если используется версификация, и объект, который должен быть помещен, включает изменения ресурса, которые находятся в противоречии со сделанными раньше каким-либо запросом (третьей стороны), сервер МОЖЕТ использовать ответ с кодом состояния 409, чтобы показать, что он не может выполнить запрос. В этом случае, объекту ответа СЛЕДУЕТ содержать список отличий двух версий в формате, определенном полем заголовка ответа Content-Type.

10.4.11 410 Удален, Gone.

Запрошенный ресурс больше не доступен на сервере, и нет никакого адреса для перенаправления запроса. Такое состояние СЛЕДУЕТ рассматривать как постоянное. Клиентам с возможностями редактирования гиперсвязей СЛЕДУЕТ удалить ссылки на запрашиваемый URI (Request-URI) после одобрения пользователем. Если сервер не знает, или не может определить, является ли такое положение постоянным или нет, то ему СЛЕДУЕТ вместо этого кода использовать код состояния 404 (Не найден, Not Found). Этот ответ является кэшируемым, если не обозначено иного.

10.4.12 411 Требуется длина, Length Required.

Сервер отказывается принимать запрос с неопределенным Content-Length. Клиент МОЖЕТ повторить запрос, если добавит допустимое поле заголовка Content-Length, содержащее длину тела сообщения (message-body) в сообщении запроса.

10.4.13 412 Предусловие неверно, Precondition Failed.

Предусловие, представленное одним или несколькими полями заголовка запроса (request-header), оказалось ложным при проверке сервером. Этот код ответа позволяет клиенту поместить предусловия на текущую метаинформацию ресурса (данные полей заголовка) и, таким образом, предотвратить применение запрошенного метода к ресурсу, отличному от того, для которого предназначен метод.

10.4.14 413 Объект запроса слишком большой, Request Entity Too Large.

Сервер отказывается обрабатывать запрос, потому что объект запроса больше, чем сервер желает или способен обработать. Сервер может закрыть соединение, чтобы не дать клиенту возможность продолжить запрос.

Если это временное состояние, то серверу СЛЕДУЕТ включить поле заголовка Retry-After для указания времени, через которое клиент может снова повторить запрос.

10.4.15 414 URI запроса слишком длинный, Request-URI Too Long.

Сервер отказывается обслуживать запрос, потому что запрашиваемый URI (Request-URI) длиннее, чем сервер желает интерпретировать. Это редкое состояние, которое, по всей вероятности, происходит только тогда, когда клиент неправильно преобразовал запрос POST к запросу GET с длинной информацией запроса, либо когда клиент попал в «черную дыру» URL перенаправления (например, перенаправленный URL префикс указывает на свой суффикс), или когда на сервер производится нападение клиентом, пытающимся эксплуатировать лазейки в секретности, имеющиеся в некоторых серверах, использующих буфера фиксированной длины для чтения или манипулирования с запрашиваемым URI (Request-URI).

10.4.16 415 Неподдерживаемый медиа тип, Unsupported Media Type.

Сервер отказывается обслуживать запрос, потому что объект запроса находится в формате, не поддерживаемом запрошенным ресурсом для запрошенного метода.

Коды состояния, начинающиеся с цифры «5» указывают случаи, в которых сервер знает, что допустил ошибку или неспособен выполнить запрос. Отвечая на запрос, за исключением запроса HEAD, серверу СЛЕДУЕТ включить объект, содержащий объяснение ошибочной ситуации и информацию, является ли это положение временным или постоянным. Агентам пользователя СЛЕДУЕТ показывать пользователю любой включенный объект. Эти коды состояния применимы к любому методу запроса.

10.5.1 500 Внутренняя ошибка сервера, Internal Server Error.

Сервер столкнулся с непредвиденным условием, которое не позволяет ему выполнить запрос.

10.5.2 501 Не реализовано, Not Implemented.

Сервер не поддерживает функциональные возможности, требуемые для выполнения запроса. Этот ответ соответствует состоянию, когда сервер не распознает метод запроса и не способен обеспечитиь его для любого ресурса.

10.5.3 502 Ошибка шлюза, Bad Gateway.

Сервер, действуя в качестве шлюза или прокси-сервера, получил недопустимый ответ от следующего сервера в цепочке запросов, к которому обратился при попытке выполнить запрос.

10.5.4 503 Сервис недоступен, Service Unavailable.

Сервер в настоящее время не способен обработать запрос из-за временной перегрузки или обслуживания сервера. Это временное условие, которое будет облегчено после некоторой задержки. Если известна продолжительность задержки, она может быть указана в заголовке Retry-After. Если Retry-After не присутствует в ответе, клиенту СЛЕДУЕТ обрабатывать этот ответ как ответ с кодом 500.

Обратите внимание: существование кода состояния 503 не подразумевает, что сервер должен использовать его, когда перегружен. Некоторые сервера могут просто закрывать соединение.

10.5.5 504 Истекло время ожидания от шлюза, Gateway Timeout.

Сервер, действуя в качестве шлюза или прокси-сервера, не получил своевременного ответа от следующего сервера в цепочке запросов, к которому обратился при попытке выполнить запрос.

10.5.6 505 Не поддерживаемая версия HTTP, HTTP Version Not Supported.

Сервер не поддерживает, или отказывается поддерживать, версию HTTP протокола, которая используется в сообщении запроса. Сервер указывает, что не способен или не желает выполнять запрос, используя ту же самую major версию, что и клиент, как описано в разделе 3.1, в других сообщениях. Ответу СЛЕДУЕТ содержать объект, описывающий, почему эта версия не поддерживается, и какие другие протоколы поддерживаются этим сервером.

Источник

Http code 204

The values of the numeric status code to HTTP requests are as follows. The data sections of messages Error, Forward and redirection responses may be used to contain human-readable diagnostic information.

Success 2xx

These codes indicate success. The body section if present is the object returned by the request. It is a MIME format object. It is in MIME format, and may only be in text/plain, text/html or one fo the formats specified as acceptable in the request.

OK 200

The request was fulfilled.

CREATED 201

Following a POST command, this indicates success, but the textual part of the response line indicates the URI by which the newly created document should be known.

Accepted 202

The request has been accepted for processing, but the processing has not been completed. The request may or may not eventually be acted upon, as it may be disallowed when processing actually takes place. there is no facility for status returns from asynchronous operations such as this.

Partial Information 203

When received in the response to a GET command, this indicates that the returned metainformation is not a definitive set of the object from a server with a copy of the object, but is from a private overlaid web. This may include annotation information about the object, for example.

No Response 204

Server has received the request but there is no information to send back, and the client should stay in the same document view. This is mainly to allow input for scripts without changing the document at the same time.

Error 4xx, 5xx

The 4xx codes are intended for cases in which the client seems to have erred, and the 5xx codes for the cases in which the server is aware that the server has erred. It is impossible to distinguish these cases in general, so the difference is only informational.

The body section may contain a document describing the error in human readable form. The document is in MIME format, and may only be in text/plain, text/html or one for the formats specified as acceptable in the request.

Bad request 400

The request had bad syntax or was inherently impossible to be satisfied.

Unauthorized 401

The parameter to this message gives a specification of authorization schemes which are acceptable. The client should retry the request with a suitable Authorization header.

PaymentRequired 402

The parameter to this message gives a specification of charging schemes acceptable. The client may retry the request with a suitable ChargeTo header.

Forbidden 403

The request is for something forbidden. Authorization will not help.

Not found 404

The server has not found anything matching the URI given

Internal Error 500

The server encountered an unexpected condition which prevented it from fulfilling the request.

Not implemented 501

The server does not support the facility required.

Service temporarily overloaded 502 (TO BE DISCUSSED)

The server cannot process the request due to a high load (whether HTTP servicing or other requests). The implication is that this is a temporary condition which maybe alleviated at other times.

Gateway timeout 503 (TO BE DISCUSSED)

This is equivalent to Internal Error 500, but in the case of a server which is in turn accessing some other service, this indicates that the respose from the other service did not return within a time that the gateway was prepared to wait. As from the point of view of the clientand the HTTP transaction the other service is hidden within the server, this maybe treated identically to Internal error 500, but has more diagnostic value.

Note: The 502 and 503 codes are new and for discussion, September 19, 1994

The codes in this section indicate action to be taken (normally automatically) by the client in order to fulfill the request.

The data requested has been assigned a new URI, the change is permanent. (N.B. this is an optimisation, which must, pragmatically, be included in this definition. Browsers with link editing capabiliy should automatically relink to the new reference, where possible)

The response contains one or more header lines of the form

Which specify alternative addresses for the object in question. The String is an optional comment field. If the response is to indicate a set of variants which each correspond to the requested URI, then the multipart/alternative wrapping may be used to distinguish different sets

The data requested actually resides under a different URL, however, the redirection may be altered on occasion (when making links to these kinds of document, the browser should default to using the Udi of the redirection document, but have the option of linking to the final document) as for «Forward».

Method 303

Note: This status code is to be specified in more detail. For the moment it is for discussion only.

Like the found response, this suggests that the client go try another network address. In this case, a different method may be used too, rather than GET.

The body-section contains the parameters to be used for the method. This allows a document to be a pointer to a complex query operation.

The body may be preceded by the following additional fields as listed.

If the client has done a conditional GET and access is allowed, but the document has not been modified since the date and time specified in If-Modified-Since field, the server responds with a 304 status code and does not send the document body to the client.

Источник

HTTP status codes : 204 OR 200 with body containing an empty object?

I’m having trouble to understand the use cases of the 204 HTTP status code. The RFC2616 says :

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The
response MAY include new or updated metainformation in the form of
entity-headers, which if present SHOULD be associated with the
requested variant.

If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent’s active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent’s active view.

The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.

Источник

The HTTP status code in IIS 7.0 and later versions

This article provides a list of the Hypertext Transfer Protocol (HTTP) status codes in Microsoft Internet Information Services (IIS) 7.0 and later versions.

Original product version: В Internet Information Services 7.0 and later versions
Original KB number: В 943891

Introduction

When you try to access content on a server that is running (IIS) 7.0, 7.5 or later versions by using the HTTP protocol, IIS returns a numeric code that indicates the status of the response. The HTTP status code is recorded in the IIS log. Additionally, the HTTP status code may be displayed in the client browser.

The HTTP status code may indicate whether a request is successful or unsuccessful. The HTTP status code may also reveal the exact reason that a request is unsuccessful.

Log file locations

IIS 7.0 and later versions put log files in the following folder by default:
inetpub\logs\Logfiles

This folder contains separate directories for each World Wide Web website. The log files are created in the directories daily and are named by using the date by default. For example, a log file may be named as exYYMMDD.log.

The HTTP status codes

This section describes the HTTP status codes that IIS 7.0 and later versions use.

This article doesn’t list every possible HTTP status code as dictated in the HTTP specification. This article includes only the HTTP status codes that IIS 7.0 and later versions can send. For example, a custom Internet Server API (ISAPI) filter or a custom HTTP module can set its own HTTP status code.

These HTTP status codes indicate a provisional response. The client computer receives one or more 1xx responses before the client computer receives a regular response.

IIS 7.0 and later versions use the following informational HTTP status codes:

These HTTP status codes indicate that the server successfully accepted the request.

IIS 7.0 and later versions use the following success HTTP status codes:

These HTTP status codes indicate that the client browser must take more action to fulfill the request. For example, the client browser may have to request a different page on the server. Or, the client browser may have to repeat the request by using a proxy server.

IIS 7.0 and later versions use the following redirection HTTP status codes:

These HTTP status codes indicate that an error has occurred and the client browser appears to be at fault. For example, the client browser may have requested a page that doesn’t exist. Or, the client browser may not have provided valid authentication information.

IIS 7.0 and later versions use the following client error HTTP status codes:

IIS 7.0 and later versions define the following HTTP status codes that indicate a more specific cause of an error 400:

IIS 7.0 and later versions define several HTTP status codes that indicate a more specific cause of an error 401. The following specific HTTP status codes are displayed in the client browser but aren’t displayed in the IIS log:

IIS 7.0 and later versions define the following HTTP status codes that indicate a more specific cause of an error 403:

IIS 7.0 and later versions define the following HTTP status codes that indicate a more specific cause of an error 404:

These HTTP status codes indicate that the server can’t complete the request because the server encounters an error.

IIS and later versions use the following server error HTTP status codes:

IIS 7.0 and later versions define the following HTTP status codes that indicate a more specific cause of an error 500:

Here is where the distributed rules configuration is read for both inbound and outbound rules.

Here is where the global rules configuration is read.

IIS 7.0 and later versions define the following HTTP status codes that indicate a more specific cause of an error 502:

IIS 7.0 and later versions define the following HTTP status codes that indicate a more specific cause of an error 503:

Common HTTP status codes and the causes

The following table describes the causes of some common HTTP status codes.

HTTP substatus codes added in IIS 8.0

SubcodeDescription
400.10Invalid X-Forwarded-For (XFF) header
400.11Invalid WebSocket request

HTTP substatus codes added in ARR 3.0.1916

SubcodeDescription
400.601Bad client request (ARR)
400.602Invalid time format (ARR)
400.603Parse range error (ARR)
400.604Client gone (ARR)
400.605Maximum number of forwards (ARR)
400.606Asynchronous competition error (ARR)
502.2Map request failure (ARR)
502.3WinHTTP asynchronous completion failure (ARR)
502.4No server (ARR)
502.5WebSocket failure (ARR)
502.6Forwarded request failure (ARR)
502.7Execute request failure (ARR)

References

For more information about HTTP status code definitions, see HTTP/1.1: Status Code Definitions.

Third-party information disclaimer

The third-party products that this article discusses are manufactured by companies that are independent of Microsoft. Microsoft makes no warranty, implied or otherwise, about the performance or reliability of these products.

Источник

Ошибки HTTP

Http code 204. Смотреть фото Http code 204. Смотреть картинку Http code 204. Картинка про Http code 204. Фото Http code 204

Во время запроса информации с удаленного веб-сервера может возникнуть ошибка. Тогда веб-сервер посылает в ответ код ошибки HTTP. Например 404 — Not Found (ресурс не найден).

Коды состояния HTTP состоят из трех цифр от 100 и до 510. Они делятся на следующие группы:

Чтобы получить сведения об ошибке, введите её код в поле поиска по странице. Для этого нажмите сочетание клавиш CTRL + F и укажите номер.

Continue
Cервер удовлетворён начальными сведениями о запросе, клиент может продолжать пересылать заголовки. Появился в HTTP/1.1.

Switching Protocols
Сервер предлагает перейти на более подходящий для указанного ресурса протокол; список предлагаемых протоколов сервер обязательно указывает в поле заголовкаUpdate. Если клиента это заинтересует, то он посылает новый запрос с указанием другого протокола. Появился в HTTP/1.1.

Processing
Запрос принят, но на его обработку понадобится длительное время. Используется сервером, чтобы клиент не разорвал соединение из-за превышения времени ожидания. Клиент при получении такого ответа должен сбросить таймер и дожидаться следующей команды в обычном режиме. Появился в WebDAV.

ОК
Успешный запрос. Если клиентом были запрошены какие-либо данные, то они находятся в заголовке и/или теле сообщения. Появился в HTTP/1.0.

Created
В результате успешного выполнения запроса был создан новый ресурс. Сервер должен указать его местоположение в заголовке Location. Серверу рекомендуется[источник не указан 336 дней] ещё указывать в заголовке характеристики созданного ресурса (например, в поле Content-Type). Если сервер не уверен, что ресурс действительно будет существовать к моменту получения данного сообщения клиентом, то лучше использовать ответ с кодом 202. Появился в HTTP/1.0.

Accepted
Запрос был принят на обработку, но она не завершена. Клиенту не обязательно дожидаться окончательной передачи сообщения, так как может быть начат очень долгий процесс. Появился в HTTP/1.0.

Non-Authoritative Information
Аналогично ответу 200, но в этом случае передаваемая информация была взята не из первичного источника (резервной копии, другого сервера и т. д.) и поэтому может быть неактуальной. Появился в HTTP/1.1.

No Content
Сервер успешно обработал запрос, но в ответе были переданы только заголовки без тела сообщения. Клиент не должен обновлять содержимое документа, но может применить к нему полученные метаданные. Появился в HTTP/1.0.

Reset Content
Сервер обязывает клиента сбросить введённые пользователем данные. Тела сообщения сервер при этом не передаёт и документ обновлять не обязательно. Появился в HTTP/1.1.

Partial Content
Сервер удачно выполнил частичный GET-запрос, возвратив только часть сообщения. В заголовке Content-Range сервер указывает байтовые диапазоны содержимого. Особое внимание при работе с подобными ответами следует уделить кэшированию. Появился в HTTP/1.1. (подробнее…)

Multi-Status
Сервер передаёт результаты выполнения сразу нескольких независимых операций. Они помещаются в само тело сообщения в виде XML-документа с объектом multistatus. Не рекомендуется размещать в этом объекте статусы из серии 1xx из-за бессмысленности и избыточности. Появился в WebDAV.

IM Used
Заголовок A-IM от клиента был успешно принят и сервер возвращает содержимое с учётом указанных параметров. Введено в RFC 3229 для дополнения протокола HTTP поддержкой дельта-кодирования.

Multiple Choices
По указанному URI существует несколько вариантов предоставления ресурса по типу MIME, по языку или по другим характеристикам. Сервер передаёт с сообщением список альтернатив, давая возможность сделать выбор клиенту автоматически или пользователю. Появился в HTTP/1.0.

Moved Permanently
Запрошенный документ был окончательно перенесен на новый URI, указанный в поле Location заголовка. Некоторые клиенты некорректно ведут себя при обработке данного кода. Появился в HTTP/1.0.

Found, Moved Temporarily
Запрошенный документ временно доступен по другому URI, указанному в заголовке в поле Location. Этот код может быть использован, например, приуправляемом сервером согласовании содержимого. Некоторые клиенты некорректно ведут себя при обработке данного кода. Введено в HTTP/1.0.

See Other
Документ по запрошенному URI нужно запросить по адресу в поле Location заголовка с использованием метода GET несмотря даже на то, что первый запрашивался иным методом. Этот код был введён вместе с 307-ым для избежания неоднозначности, чтобы сервер был уверен, что следующий ресурс будет запрошен методом GET. Например, на веб-странице есть поле ввода текста для быстрого перехода и поиска. После ввода данных браузер делает запрос методом POST, включая в тело сообщения введённый текст. Если обнаружен документ с введённым названием, то сервер отвечает кодом 303, указав в заголовке Location его постоянный адрес. Тогда браузер гарантировано его запросит методом GET для получения содержимого. В противном случае сервер просто вернёт клиенту страницу с результатами поиска. Введено в HTTP/1.1.

Not Modified
Сервер возвращает такой код, если клиент запросил документ методом GET, использовал заголовок If-Modified-Since или If-None-Match и документ не изменился с указанного момента. При этом сообщение сервера не должно содержать тела. Появился в HTTP/1.0.

Use Proxy
Запрос к запрашиваемому ресурсу должен осуществляться через прокси-сервер, URI которого указан в поле Location заголовка. Данный код ответа могут использовать только исходные HTTP-сервера (не прокси). Введено в HTTP/1.1.

(зарезервировано)
использовавшийся раньше код ответа, в настоящий момент зарезервирован. Упомянут в RFC 2616 (обновление HTTP/1.1).

Temporary Redirect
Запрашиваемый ресурс на короткое время доступен по другому URI, указанный в поле Location заголовка. Этот код был введён вместе с 303 вместо 302-го для избежания неоднозначности. Введено в RFC 2616 (обновление HTTP/1.1).

Bad Request
Сервер обнаружил в запросе клиента синтаксическую ошибку. Появился в HTTP/1.0.

Unauthorized
Для доступа к запрашиваемому ресурсу требуется аутентификация. В заголовке ответ должен содержать поле WWW-Authenticate с перечнем условий аутентификации. Клиент может повторить запрос, включив в заголовок сообщения поле Authorization с требуемыми для аутентификации данными.

Payment Required
Предполагается использовать в будущем. В настоящий момент не используется. Этот код предусмотрен для платных пользовательских сервисов, а не для хостинговыхкомпаний. Имеется в виду, что эта ошибка не будет выдана хостинговым провайдером в случае просроченной оплаты его услуг. Зарезервирован, начиная с HTTP/1.1.

Not Found
Самая распространенная ошибка при пользовании Интернетом, основная причина — ошибка в написании адреса Web-страницы. Сервер понял запрос, но не нашёл соответствующего ресурса по указанному URI. Если серверу известно, что по этому адресу был документ, то ему желательно использовать код 410. Ответ 404 может использоваться вместо 403, если требуется тщательно скрыть от посторонних глаз определённые ресурсы. Появился в HTTP/1.0.

Method Not Allowed
Указанный клиентом метод нельзя применить к текущему ресурсу. В ответе сервер должен указать доступные методы в заголовке Allow, разделив их запятой. Эту ошибку сервер должен возвращать, если метод ему известен, но он не применим именно к указанному в запросе ресурсу, если же указанный метод не применим на всём сервере, то клиенту нужно вернуть код 501 (Not Implemented). Появился в HTTP/1.1.

Not Acceptable
Запрошенный URI не может удовлетворить переданным в заголовке характеристикам. Если метод был не HEAD, то сервер должен вернуть список допустимых характеристик для данного ресурса. Появился в HTTP/1.1.

Proxy Authentication Required
Ответ аналогичен коду 401 за исключением того, что аутентификация производится для прокси-сервера. Механизм аналогичен идентификации на исходном сервере. Появился в HTTP/1.1.

Request Timeout
Время ожидания сервером передачи от клиента истекло. Клиент может повторить аналогичный предыдущему запрос в любое время. Например, такая ситуация может возникнуть при загрузке на сервер объёмного файла методом POST или PUT. В какой-то момент передачи источник данных перестал отвечать, например, из-за повреждения компакт-диска или потеря связи с другим компьютером в локальной сети. Пока клиент ничего не передаёт, ожидая от него ответа, соединение с сервером держится. Через некоторое время сервер может закрыть соединение со своей стороны, чтобы дать возможность другим клиентам сделать запрос. Этот ответ не возвращается, когда клиент принудительно остановил передачу по команде пользователя или соединение прервалось по каким-то иным причинам, так как ответ уже послать невозможно. Появился в HTTP/1.1.

Conflict
Запрос не может быть выполнен из-за конфликтного обращения к ресурсу. Такое возможно, например, когда два клиента пытаются изменить ресурс с помощью метода PUT.Появился в HTTP/1.1.

Gone
Такой ответ сервер посылает, если ресурс раньше был по указанному URL, но был удалён и теперь недоступен. Серверу в этом случае неизвестно и местоположение альтернативного документа, например, копии). Если у сервера есть подозрение, что документ в ближайшее время может быть восстановлен, то лучше клиенту передать код 404. Появился в HTTP/1.1.

Length Required
Для указанного ресурса клиент должен указать Content-Length в заголовке запроса. Без указания этого поля не стоит делать повторную попытку запроса к серверу по данному URI. Такой ответ естественен для запросов типа POST и PUT. Например, если по указанному URI производится загрузка файлов, а на сервере стоит ограничение на их объём. Тогда разумней будет проверить в самом начале заголовок Content-Length и сразу отказать в загрузке, чем провоцировать бессмысленную нагрузку, разрывая соединение, когда клиент действительно пришлёт слишком объёмное сообщение. Появился в HTTP/1.1.

Precondition Failed
Возвращается, если ни одно из условных полей заголовка[неизвестный термин] запроса не было выполнено. Появился в HTTP/1.1.

Request Entity Too Large
Возвращается в случае, если сервер отказывается обработать запрос по причине слишком большого размера тела запроса. Сервер может закрыть соединение, чтобы прекратить дальнейшую передачу запроса. Если проблема временная, то рекомендуется в ответ сервера включить заголовок Retry-After с указанием времени, по истечении которого можно повторить аналогичный запрос. Появился в HTTP/1.1.

Request-URL Too Long
Сервер не может обработать запрос из-за слишком длинного указанного URL. Такую ошибку можно спровоцировать, например, когда клиент пытается передать длинные параметры через метод GET, а не POST. Появился в HTTP/1.1.

Unsupported Media Type
По каким-то причинам сервер отказывается работать с указанным типом данных при данном методе. Появился в HTTP/1.1.

Requested Range Not Satisfiabl
В поле Range заголовка запроса был указан диапазон за пределами ресурса и отсутствует поле If-Range. Если клиент передал байтовый диапазон, то сервер может вернуть реальный размер в поле Content-Range заголовка. Данный ответ не следует использовать при передаче типа multipart/byteranges[источник не указан 336 дней]. Введено в RFC 2616 (обновление HTTP/1.1).

Expectation Failed
По каким-то причинам сервер не может удовлетворить значению поля Expect заголовка запроса. Введено в RFC 2616 (обновление HTTP/1.1).

Unprocessable Entity
Сервер успешно принял запрос, может работать с указанным видом данных, в теле запроса XML-документ имеет верный синтаксис, но имеется какая-то логическая ошибка, из-за которой невозможно произвести операцию над ресурсом. Введено в WebDAV.

Locked
Целевой ресурс из запроса заблокирован от применения к нему указанного метода. Введено в WebDAV.

Failed Dependency
Реализация текущего запроса может зависеть от успешности выполнения другой операции. Если она не выполнена и из-за этого нельзя выполнить текущий запрос, то сервер вернёт этот код. Введено в WebDAV.

Unordered Collection —
Посылается, если клиент послал запрос, обозначив положение в неотсортированной коллекции или используя порядок следования элементов, отличный от серверного[уточнить]. Введено в черновике по WebDAV Advanced Collections Protocol[14].

Upgrade Required
Сервер указывает клиенту на необходимость обновить протокол. Заголовок ответа должен содержать правильно сформированные поля Upgrade и Connection. Введено вRFC 2817 для возможности перехода к TLS посредством HTTP.

Retry With
Возвращается сервером, если для обработки запроса от клиента поступило недостаточно информации. При этом в заголовок ответа помещается поле Ms-Echo-Request. Введено корпорацией Microsoft для WebDAV. В настоящий момент как минимум используется программой Microsoft Money.

Unrecoverable Error
Возвращается сервером, если обработка запроса вызывает некорректируемые сбои в таблицах баз данных[источник не указан 336 дней]. Введено корпорацией Microsoftдля WebDAV.

Internal Server Error
Любая внутренняя ошибка сервера, которая не входит в рамки остальных ошибок класса. Появился в HTTP/1.0.

Not Implemented
Сервер не поддерживает возможностей, необходимых для обработки запроса. Типичный ответ для случаев, когда сервер не понимает указанный в запросе метод. Если же метод серверу известен, но он не применим к данному ресурсу, то нужно вернуть ответ 405. Появился в HTTP/1.0.

Bad Gateway
Сервер, выступая в роли шлюза или прокси-сервера, получил недействительное ответное сообщение от вышестоящего сервера. Появился в HTTP/1.0.

Service Unavailable
Сервер временно не имеет возможности обрабатывать запросы по техническим причинам (обслуживание, перегрузка и прочее). В поле Retry-After заголовка сервер может указать время, через которое клиенту рекомендуется повторить запрос. Хотя во время перегрузки очевидным кажется сразу разрывать соединение, эффективней может оказаться установка большого значения поля Retry-After для уменьшения частоты избыточных запросов. Появился в HTTP/1.0.

Gateway Timeout
Сервер в роли шлюза или прокси-сервера не дождался ответа от вышестоящего сервера для завершения текущего запроса. Появился в HTTP/1.1.

HTTP Version Not Supported
Сервер не поддерживает или отказывается поддерживать указанную в запросе версию протокола HTTP. Появился в HTTP/1.1.

Variant Also Negotiates
В результате ошибочной конфигурации выбранный вариант указывает сам на себя, из-за чего процесс связывания прерывается. Экспериментальное. Введено в RFC 2295 для дополнения протокола HTTP технологией Transparent Content Negotiation.

Insufficient Storage
Не хватает места для выполнения текущего запроса. Проблема может быть временной. Введено в WebDAV.

Bandwidth Limit Exceeded
Используется при превышении веб-площадкой отведённого ей ограничения на потребление трафика. В данном случае владельцу площадки следует обратиться к своему хостинг-провайдеру. В настоящий момент данный код не описан ни в одном RFC и используется только модулем «bw/limited», входящим в панель управления хостингом cPanel, где и был введён.

Not Extended
На сервере отсутствует расширение, которое желает использовать клиент. Сервер может дополнительно передать информацию о доступных ему расширениях. Введено в RFC 2774 для дополнения протокола HTTP поддержкой расширений.

Источник

HTTP Status Codes

This page is created from HTTP status code information found at ietf.org and Wikipedia. Click on the category heading or the status code link to read more.

1xx Informational

This class of status code indicates a provisional response, consisting only of the Status-Line and optional headers, and is terminated by an empty line. There are no required headers for this class of status code. Since HTTP/1.0 did not define any 1xx status codes, servers MUST NOT send a 1xx response to an HTTP/1.0 client except under experimental conditions.

A client MUST be prepared to accept one or more 1xx status responses prior to a regular response, even if the client does not expect a 100 (Continue) status message. Unexpected 1xx status responses MAY be ignored by a user agent.

Proxies MUST forward 1xx responses, unless the connection between the proxy and its client has been closed, or unless the proxy itself requested the generation of the 1xx response. (For example, if a proxy adds a «Expect: 100-continue» field when it forwards a request, then it need not forward the corresponding 100 (Continue) response(s).)

Wikipedia

Request received, continuing process.

This class of status code indicates a provisional response, consisting only of the Status-Line and optional headers, and is terminated by an empty line. Since HTTP/1.0 did not define any 1xx status codes, servers must not send a 1xx response to an HTTP/1.0 client except under experimental conditions.

The client SHOULD continue with its request. This interim response is used to inform the client that the initial part of the request has been received and has not yet been rejected by the server. The client SHOULD continue by sending the remainder of the request or, if the request has already been completed, ignore this response. The server MUST send a final response after the request has been completed. See section 8.2.3 for detailed discussion of the use and handling of this status code.

Wikipedia

This means that the server has received the request headers, and that the client should proceed to send the request body (in the case of a request for which a body needs to be sent; for example, a POST request). If the request body is large, sending it to a server when a request has already been rejected based upon inappropriate headers is inefficient. To have a server check if the request could be accepted based on the request’s headers alone, a client must send Expect: 100-continue as a header in its initial request and check if a 100 Continue status code is received in response before continuing (or receive 417 Expectation Failed and not continue).

The server understands and is willing to comply with the client’s request, via the Upgrade message header field (section 14.42), for a change in the application protocol being used on this connection. The server will switch protocols to those defined by the response’s Upgrade header field immediately after the empty line which terminates the 101 response.

The protocol SHOULD be switched only when it is advantageous to do so. For example, switching to a newer version of HTTP is advantageous over older versions, and switching to a real-time, synchronous protocol might be advantageous when delivering resources that use such features.

Wikipedia

This means the requester has asked the server to switch protocols and the server is acknowledging that it will do so.

The 102 (Processing) status code is an interim response used to inform the client that the server has accepted the complete request, but has not yet completed it. This status code SHOULD only be sent when the server has a reasonable expectation that the request will take significant time to complete. As guidance, if a method is taking longer than 20 seconds (a reasonable, but arbitrary value) to process the server SHOULD return a 102 (Processing) response. The server MUST send a final response after the request has been completed.

Methods can potentially take a long period of time to process, especially methods that support the Depth header. In such cases the client may time-out the connection while waiting for a response. To prevent this the server may return a 102 (Processing) status code to indicate to the client that the server is still processing the method.

Wikipedia

As a WebDAV request may contain many sub-requests involving file operations, it may take a long time to complete the request. This code indicates that the server has received and is processing the request, but no response is available yet. This prevents the client from timing out and assuming the request was lost.

2xx Success

This class of status code indicates that the client’s request was successfully received, understood, and accepted.

Wikipedia

This class of status codes indicates the action requested by the client was received, understood, accepted and processed successfully.

Wikipedia

Standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource. In a POST request the response will contain an entity describing or containing the result of the action.

General status code. Most common code used to indicate success.

The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field. The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. The origin server MUST create the resource before returning the 201 status code. If the action cannot be carried out immediately, the server SHOULD respond with 202 (Accepted) response instead.

A 201 response MAY contain an ETag response header field indicating the current value of the entity tag for the requested variant just created, see section 14.19.

Wikipedia

The request has been fulfilled and resulted in a new resource being created.

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

The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. There is no facility for re-sending a status code from an asynchronous operation such as this.

The 202 response is intentionally non-committal. Its purpose is to allow a server to accept a request for some other process (perhaps a batch-oriented process that is only run once per day) without requiring that the user agent’s connection to the server persist until the process is completed. The entity returned with this response SHOULD include an indication of the request’s current status and either a pointer to a status monitor or some estimate of when the user can expect the request to be fulfilled.

Wikipedia

The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place.

The returned metainformation in the entity-header is not the definitive set as available from the origin server, but is gathered from a local or a third-party copy. The set presented MAY be a subset or superset of the original version. For example, including local annotation information about the resource might result in a superset of the metainformation known by the origin server. Use of this response code is not required and is only appropriate when the response would otherwise be 200 (OK).

Wikipedia

The server successfully processed the request, but is returning information that may be from another source.

Not present in HTTP/1.0: available since HTTP/1.1

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent’s active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent’s active view.

The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.

Wikipedia

The server successfully processed the request, but is not returning any content.

Status when wrapped responses (e.g. JSEND) are not used and nothing is in the body (e.g. DELETE).

The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent. This response is primarily intended to allow input for actions to take place via user input, followed by a clearing of the form in which the input is given so that the user can easily initiate another input action. The response MUST NOT include an entity.

Wikipedia

The server successfully processed the request, but is not returning any content. Unlike a 204 response, this response requires that the requester reset the document view.

The server has fulfilled the partial GET request for the resource. The request MUST have included a Range header field (section 14.35) indicating the desired range, and MAY have included an If-Range header field (section 14.27) to make the request conditional.

The response MUST include the following header fields:

If the 206 response is the result of an If-Range request that used a strong cache validator (see section 13.3.3), the response SHOULD NOT include other entity-headers. If the response is the result of an If-Range request that used a weak validator, the response MUST NOT include other entity-headers; this prevents inconsistencies between cached entity-bodies and updated headers. Otherwise, the response MUST include all of the entity-headers that would have been returned with a 200 (OK) response to the same request.

A cache MUST NOT combine a 206 response with other previously cached content if the ETag or Last-Modified headers do not match exactly, see 13.5.4.

A cache that does not support the Range and Content-Range headers MUST NOT cache 206 (Partial) responses.

Wikipedia

The server is delivering only part of the resource due to a range header sent by the client. The range header is used by tools like wget to enable resuming of interrupted downloads, or split a download into multiple simultaneous streams.

The 207 (Multi-Status) status code provides status for multiple independent operations (see section 11 for more information).

Wikipedia

The message body that follows is an XML message and can contain a number of separate response codes, depending on how many sub-requests were made.

The 208 (Already Reported) status code can be used inside a DAV: propstat response element to avoid enumerating the internal members of multiple bindings to the same collection repeatedly. For each binding to a collection inside the request’s scope, only one will be reported with a 200 status, while subsequent DAV:response elements for all other bindings will use the 208 status, and no DAV:response elements for their descendants are included.

Wikipedia

The members of a DAV binding have already been enumerated in a previous reply to this request, and are not being included again.

The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance. The actual current instance might not be available except by combining this response with other previous or future responses, as appropriate for the specific instance-manipulation(s). If so, the headers of the resulting instance are the result of combining the headers from the status-226 response and the other instances, following the rules in section 13.5.3 of the HTTP/1.1 specification.

The request MUST have included an A-IM header field listing at least one instance-manipulation. The response MUST include an Etag header field giving the entity tag of the current instance.

A response received with a status code of 226 MAY be stored by a cache and used in reply to a subsequent request, subject to the HTTP expiration mechanism and any Cache-Control headers, and to the requirements in section 10.6.

A response received with a status code of 226 MAY be used by a cache, in conjunction with a cache entry for the base instance, to create a cache entry for the current instance.

Wikipedia

The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.

3xx Redirection

This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. The action required MAY be carried out by the user agent without interaction with the user if and only if the method used in the second request is GET or HEAD. A client SHOULD detect infinite redirection loops, since such loops generate network traffic for each redirection.

Note: previous versions of this specification recommended a maximum of five redirections. Content developers should be aware that there might be clients that implement such a fixed limitation.

Wikipedia

The client must take additional action to complete the request.

This class of status code indicates that further action needs to be taken by the user agent in order to fulfil the request. The action required may be carried out by the user agent without interaction with the user if and only if the method used in the second request is GET or HEAD. A user agent should not automatically redirect a request more than five times, since such redirections usually indicate an infinite loop.

The requested resource corresponds to any one of a set of representations, each with its own specific location, and agent- driven negotiation information (section 12) is being provided so that the user (or user agent) can select a preferred representation and redirect its request to that location.

Unless it was a HEAD request, the response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content- Type header field. Depending upon the format and the capabilities of the user agent, selection of the most appropriate choice MAY be performed automatically. However, this specification does not define any standard for such automatic selection.

If the server has a preferred choice of representation, it SHOULD include the specific URI for that representation in the Location field; user agents MAY use the Location field value for automatic redirection. This response is cacheable unless indicated otherwise.

Wikipedia

Indicates multiple options for the resource that the client may follow. It, for instance, could be used to present different format options for video, list files with different extensions, or word sense disambiguation.

The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. Clients with link editing capabilities ought to automatically re-link references to the Request-URI to one or more of the new references returned by the server, where possible. This response is cacheable unless indicated otherwise.

The new permanent URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).

If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Note: When automatically redirecting a POST request after receiving a 301 status code, some existing HTTP/1.0 user agents will erroneously change it into a GET request.

Wikipedia

This and all future requests should be directed to the given URI.

The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.

The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).

If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Note: RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.

Wikipedia

This is an example of industry practice contradicting the standard.[2] The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect (the original describing phrase was «Moved Temporarily»), but popular browsers implemented 302 with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 to distinguish between the two behaviours. However, some Web applications and frameworks use the 302 status code as if it were the 303.

The response to the request can be found under a different URI and SHOULD be retrieved using a GET method on that resource. This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource. The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.

The different URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).

Note: Many pre-HTTP/1.1 user agents do not understand the 303 status. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303.

Wikipedia

The response to the request can be found under another URI using a GET method. When received in response to a POST (or PUT/DELETE), it should be assumed that the server has received the data and the redirect should be issued with a separate GET message.

If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code. The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.

The response MUST include the following header fields:

If a clockless origin server obeys these rules, and proxies and clients add their own Date to any response received without one (as already specified by [RFC 2068], section 14.19), caches will operate correctly.

If the conditional GET used a strong cache validator (see section 13.3.3), the response SHOULD NOT include other entity-headers. Otherwise (i.e., the conditional GET used a weak validator), the response MUST NOT include other entity-headers; this prevents inconsistencies between cached entity-bodies and updated headers.

If a 304 response indicates an entity not currently cached, then the cache MUST disregard the response and repeat the request without the conditional.

If a cache uses a received 304 response to update a cache entry, the cache MUST update the entry to reflect any new field values given in the response.

Wikipedia

Indicates the resource has not been modified since last requested. Typically, the HTTP client provides a header like the If-Modified-Since header to provide a time against which to compare. Using this saves bandwidth and reprocessing on both the server and client, as only the header data must be sent and received in comparison to the entirety of the page being re-processed by the server, then sent again using more bandwidth of the server and client.

Used for 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 body on the response.

The requested resource MUST be accessed through the proxy given by the Location field. The Location field gives the URI of the proxy. The recipient is expected to repeat this single request via the proxy. 305 responses MUST only be generated by origin servers.

Note: RFC 2068 was not clear that 305 was intended to redirect a single request, and to be generated by origin servers only. Not observing these limitations has significant security consequences.

Wikipedia

Many HTTP clients (such as Mozilla and Internet Explorer) do not correctly handle responses with this status code, primarily for security reasons.

The 306 status code was used in a previous version of the specification, is no longer used, and the code is reserved.

Wikipedia

No longer used. Originally meant «Subsequent requests should use the specified proxy.»

The requested resource resides temporarily under a different URI. Since the redirection MAY be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.

If the 307 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Wikipedia

In this case, the request should be repeated with another URI; however, future requests can still use the original URI. In contrast to 302, the request method should not be changed when reissuing the original request. For instance, a POST request must be repeated using another POST request.

Wikipedia

The request, and all future requests should be repeated using another URI. 307 and 308 (as proposed) parallel the behaviours of 302 and 301, but do not require the HTTP method to change. So, for example, submitting a form to a permanently redirected resource may continue smoothly.

4xx Client Error

The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. User agents SHOULD display any included entity to the user.

If the client is sending data, a server implementation using TCP SHOULD be careful to ensure that the client acknowledges receipt of the packet(s) containing the response, before the server closes the input connection. If the client continues sending data to the server after the close, the server’s TCP stack will send a reset packet to the client, which may erase the client’s unacknowledged input buffers before they can be read and interpreted by the HTTP application.

Wikipedia

The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server should include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. User agents should display any included entity to the user.

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

Wikipedia

The request cannot be fulfilled due to bad syntax.

General error when fulfilling the request would cause an invalid state. Domain validation errors, missing data, etc. are some examples.

The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information. HTTP access authentication is explained in «HTTP Authentication: Basic and Digest Access Authentication».

Wikipedia

Similar to 403 Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource. See Basic access authentication and Digest access authentication.

Error code response for missing or invalid authentication token.

This code is reserved for future use.

Wikipedia

Reserved for future use. The original intention was that this code might be used as part of some form of digital cash or micropayment scheme, but that has not happened, and this code is not usually used. As an example of its use, however, Apple’s MobileMe service generates a 402 error («httpStatusCode:402» in the Mac OS X Console log) if the MobileMe account is delinquent.

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

Wikipedia

The request was a legal request, but the server is refusing to respond to it. Unlike a 401 Unauthorized response, authenticating will make no difference.

Error code for user not authorized to perform the operation or the resource is unavailable for some reason (e.g. time constraints, etc.).

The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.

Wikipedia

The requested resource could not be found but may be available again in the future. Subsequent requests by the client are permissible.

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.

The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.

Wikipedia

A request was made of a resource using a request method not supported by that resource; for example, using GET on a form which requires data to be presented via POST, or using PUT on a read-only resource.

The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.

Unless it was a HEAD request, the response SHOULD include an entity containing a list of available entity characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. Depending upon the format and the capabilities of the user agent, selection of the most appropriate choice MAY be performed automatically. However, this specification does not define any standard for such automatic selection.

Note: HTTP/1.1 servers are allowed to return responses which are not acceptable according to the accept headers sent in the request. In some cases, this may even be preferable to sending a 406 response. User agents are encouraged to inspect the headers of an incoming response to determine if it is acceptable.

If the response could be unacceptable, a user agent SHOULD temporarily stop receipt of more data and query the user for a decision on further actions.

Wikipedia

The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request.

This code is similar to 401 (Unauthorized), but indicates that the client must first authenticate itself with the proxy. The proxy MUST return a Proxy-Authenticate header field (section 14.33) containing a challenge applicable to the proxy for the requested resource. The client MAY repeat the request with a suitable Proxy-Authorization header field (section 14.34). HTTP access authentication is explained in «HTTP Authentication: Basic and Digest Access Authentication».

Wikipedia

The client must first authenticate itself with the proxy.

The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.

Wikipedia

The server timed out waiting for the request. According to W3 HTTP specifications: «The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.»

The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.

Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can’t complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.

Wikipedia

Indicates that the request could not be processed because of conflict in the request, such as an edit conflict.

Whenever a resource conflict would be caused by fulfilling the request. Duplicate entries and deleting root objects when cascade-delete is not supported are a couple of examples.

The requested resource is no longer available at the server and no forwarding address is known. This condition is expected to be considered permanent. Clients with link editing capabilities SHOULD delete references to the Request-URI after user approval. If the server does not know, or has no facility to determine, whether or not the condition is permanent, the status code 404 (Not Found) SHOULD be used instead. This response is cacheable unless indicated otherwise.

Wikipedia

Indicates that the resource requested is no longer available and will not be available again. This should be used when a resource has been intentionally removed and the resource should be purged. Upon receiving a 410 status code, the client should not request the resource again in the future. Clients such as search engines should remove the resource from their indices. Most use cases do not require clients and search engines to purge the resource, and a «404 Not Found» may be used instead.

The server refuses to accept the request without a defined Content- Length. The client MAY repeat the request if it adds a valid Content-Length header field containing the length of the message-body in the request message.

Wikipedia

The request did not specify the length of its content, which is required by the requested resource.

The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server. This response code allows the client to place preconditions on the current resource metainformation (header field data) and thus prevent the requested method from being applied to a resource other than the one intended.

Wikipedia

The server does not meet one of the preconditions that the requester put on the request.

The server is refusing to process a request because the request entity is larger than the server is willing or able to process. The server MAY close the connection to prevent the client from continuing the request.

If the condition is temporary, the server SHOULD include a Retry- After header field to indicate that it is temporary and after what time the client MAY try again.

Wikipedia

The request is larger than the server is willing or able to process.

The server is refusing to service the request because the Request-URI is longer than the server is willing to interpret. This rare condition is only likely to occur when a client has improperly converted a POST request to a GET request with long query information, when the client has descended into a URI «black hole» of redirection (e.g., a redirected URI prefix that points to a suffix of itself), or when the server is under attack by a client attempting to exploit security holes present in some servers using fixed-length buffers for reading or manipulating the Request-URI.

Wikipedia

The URI provided was too long for the server to process.

The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.

Wikipedia

The request entity has a media type which the server or resource does not support. For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.

A server SHOULD return a response with this status code if a request included a Range request-header field (section 14.35), and none of the range-specifier values in this field overlap the current extent of the selected resource, and the request did not include an If-Range request-header field. (For byte-ranges, this means that the first- byte-pos of all of the byte-range-spec values were greater than the current length of the selected resource.)

When this status code is returned for a byte-range request, the response SHOULD include a Content-Range entity-header field specifying the current length of the selected resource (see section 14.16). This response MUST NOT use the multipart/byteranges content- type.

Wikipedia

The client has asked for a portion of the file, but the server cannot supply that portion. For example, if the client asked for a part of the file that lies beyond the end of the file.

The expectation given in an Expect request-header field (see section 14.20) could not be met by this server, or, if the server is a proxy, the server has unambiguous evidence that the request could not be met by the next-hop server.

Wikipedia

The server cannot meet the requirements of the Expect request-header field.

Wikipedia

This code was defined in 1998 as one of the traditional IETF April Fools’ jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol, and is not expected to be implemented by actual HTTP servers. However, known implementations do exist. An Nginx HTTP server uses this code to simulate goto-like behaviour in its configuration.

Wikipedia

Returned by the Twitter Search and Trends API when the client is being rate limited. The text is a quote from ‘Demolition Man’ and the ‘420’ code is likely a reference to this number’s association with marijuana. Other services may wish to implement the 429 Too Many Requests response code instead.

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

Wikipedia

The request was well-formed but was unable to be followed due to semantic errors.

The 423 (Locked) status code means the source or destination resource of a method is locked. This response SHOULD contain an appropriate precondition or postcondition code, such as ‘lock-token-submitted’ or ‘no-conflicting-lock’.

Wikipedia

The resource that is being accessed is locked.

The 424 (Failed Dependency) status code means that the method could not be performed on the resource because the requested action depended on another action and that action failed. For example, if a command in a PROPPATCH method fails, then, at minimum, the rest of the commands will also fail with 424 (Failed Dependency).

Wikipedia

The request failed due to failure of a previous request (e.g. a PROPPATCH).

Slein, J., Whitehead, E.J., et al., «WebDAV Advanced Collections Protocol», Work In Progress.

Wikipedia

Defined in drafts of «WebDAV Advanced Collections Protocol», but not present in «Web Distributed Authoring and Versioning (WebDAV) Ordered Collections Protocol».

Reliable, interoperable negotiation of Upgrade features requires an unambiguous failure signal. The 426 Upgrade Required status code allows a server to definitively state the precise protocol extensions a given resource must be served with.

Wikipedia

The client should switch to a different protocol such as TLS/1.0.

The 428 status code indicates that the origin server requires the request to be conditional.

Its typical use is to avoid the «lost update» problem, where a client GETs a resource’s state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict. By requiring requests to be conditional, the server can assure that clients are working with the correct copies.

Responses using this status code SHOULD explain how to resubmit the request successfully.

The 428 status code is optional; clients cannot rely upon its use to prevent «lost update» conflicts.

Wikipedia

The origin server requires the request to be conditional. Intended to prevent «the «lost update» problem, where a client GETs a resource’s state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.

The 429 status code indicates that the user has sent too many requests in a given amount of time («rate limiting»).

The response representations SHOULD include details explaining the condition, and MAY include a Retry-After header indicating how long to wait before making a new request.

When a server is under attack or just receiving a very large number of requests from a single party, responding to each with a 429 status code will consume resources.

Therefore, servers are not required to use the 429 status code; when limiting resource usage, it may be more appropriate to just drop connections, or take other steps.

Wikipedia

The user has sent too many requests in a given amount of time. Intended for use with rate limiting schemes.

The 431 status code indicates that the server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields.

It can be used both when the set of request header fields in total are too large, and when a single header field is at fault. In the latter case, the response representation SHOULD specify which header field was too large.

Servers are not required to use the 431 status code; when under attack, it may be more appropriate to just drop connections, or take other steps.

Wikipedia

The server is unwilling to process the request because either an individual header field, or all the header fields collectively, are too large.

Wikipedia

An Nginx HTTP server extension. The server returns no information to the client and closes the connection (useful as a deterrent for malware).

Wikipedia

A Microsoft extension. The request should be retried after performing the appropriate action.

Wikipedia

A Microsoft extension. This error is given when Windows Parental Controls are turned on and are blocking access to the given webpage.

Wikipedia

Intended to be used when resource access is denied for legal reasons, e.g. censorship or government-mandated blocked access. A reference to the 1953 dystopian novel Fahrenheit 451, where books are outlawed, and the autoignition temperature of paper, 451В°F.

Wikipedia

An Nginx HTTP server extension. This code is introduced to log the case when the connection is closed by client while HTTP server is processing its request, making server unable to send the HTTP header back.

5xx Server Error

Response status codes beginning with the digit «5» indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. User agents SHOULD display any included entity to the user. These response codes are applicable to any request method.

Wikipedia

The server failed to fulfill an apparently valid request.

Response status codes beginning with the digit «5» indicate cases in which the server is aware that it has encountered an error or is otherwise incapable of performing the request. Except when responding to a HEAD request, the server should include an entity containing an explanation of the error situation, and indicate whether it is a temporary or permanent condition. Likewise, user agents should display any included entity to the user. These response codes are applicable to any request method.

The server encountered an unexpected condition which prevented it from fulfilling the request.

Wikipedia

A generic error message, given when no more specific message is suitable.

The general catch-all error when the server-side throws an exception.

The server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource.

Wikipedia

The server either does not recognise the request method, or it lacks the ability to fulfill the request.

The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.

Wikipedia

The server was acting as a gateway or proxy and received an invalid response from the upstream server.

The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. If known, the length of the delay MAY be indicated in a Retry-After header. If no Retry-After is given, the client SHOULD handle the response as it would for a 500 response.

Note: The existence of the 503 status code does not imply that a server must use it when becoming overloaded. Some servers may wish to simply refuse the connection.

Wikipedia

The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state.

The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed to access in attempting to complete the request.

Note: Note to implementors: some deployed proxies are known to return 400 or 500 when DNS lookups time out.

Wikipedia

The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.

The server does not support, or refuses to support, the HTTP protocol version that was used in the request message. The server is indicating that it is unable or unwilling to complete the request using the same major version as the client, as described in section 3.1, other than with this error message. The response SHOULD contain an entity describing why that version is not supported and what other protocols are supported by that server.

Wikipedia

The server does not support the HTTP protocol version used in the request.

The 506 status code indicates that the server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.

Wikipedia

Transparent content negotiation for the request results in a circular reference.

The 507 (Insufficient Storage) status code means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request. This condition is considered to be temporary. If the request that received this status code was the result of a user action, the request MUST NOT be repeated until it is requested by a separate user action.

Wikipedia

The server is unable to store the representation needed to complete the request.

The 508 (Loop Detected) status code indicates that the server terminated an operation because it encountered an infinite loop while processing a request with «Depth: infinity». This status indicates that the entire operation failed.

Wikipedia

The server detected an infinite loop while processing the request (sent in lieu of 208).

Wikipedia

This status code, while used by many servers, is not specified in any RFCs.

The policy for accessing the resource has not been met in the request. The server should send back all the information necessary for the client to issue an extended request. It is outside the scope of this specification to specify how the extensions inform the client.

If the 510 response contains information about extensions that were not present in the initial request then the client MAY repeat the request if it has reason to believe it can fulfill the extension policy by modifying the request according to the information provided in the 510 response. Otherwise the client MAY present any entity included in the 510 response to the user, since that entity may include relevant diagnostic information.

Wikipedia

Further extensions to the request are required for the server to fulfill it.

The 511 status code indicates that the client needs to authenticate to gain network access.

The response representation SHOULD contain a link to a resource that allows the user to submit credentials (e.g. with a HTML form).

Note that the 511 response SHOULD NOT contain a challenge or the login interface itself, because browsers would show the login interface as being associated with the originally requested URL, which may cause confusion.

The 511 status SHOULD NOT be generated by origin servers; it is intended for use by intercepting proxies that are interposed as a means of controlling access to the network.

Responses with the 511 status code MUST NOT be stored by a cache.

The 511 status code is designed to mitigate problems caused by «captive portals» to software (especially non-browser agents) that is expecting a response from the server that a request was made to, not the intervening network infrastructure. It is not intended to encouraged deployment of captive portals, only to limit the damage caused by them.

A network operator wishing to require some authentication, acceptance of terms or other user interaction before granting access usually does so by identifing clients who have not done so («unknown clients») using their MAC addresses.

Unknown clients then have all traffic blocked, except for that on TCP port 80, which is sent to a HTTP server (the «login server») dedicated to «logging in» unknown clients, and of course traffic to the login server itself.

In common use, a response carrying the 511 status code will not come from the origin server indicated in the request’s URL. This presents many security issues; e.g., an attacking intermediary may be inserting cookies into the original domain’s name space, may be observing cookies or HTTP authentication credentials sent from the user agent, and so on.

However, these risks are not unique to the 511 status code; in other words, a captive portal that is not using this status code introduces the same issues.

Also, note that captive portals using this status code on an SSL or TLS connection (commonly, port 443) will generate a certificate error on the client.

Wikipedia

The client needs to authenticate to gain network access. Intended for use by intercepting proxies used to control access to the network (e.g., «captive portals» used to require agreement to Terms of Service before granting full Internet access via a Wi-Fi hotspot).

Wikipedia

This status code is not specified in any RFCs, but is used by some HTTP proxies to signal a network read timeout behind the proxy to a client in front of the proxy.

Wikipedia

This status code is not specified in any RFCs, but is used by some HTTP proxies to signal a network connect timeout behind the proxy to a client in front of the proxy.

«Top 10» HTTP Status Code. More REST service-specific information is contained in the entry.

Http code 204. Смотреть фото Http code 204. Смотреть картинку Http code 204. Картинка про Http code 204. Фото Http code 204
This work by RestApiTutorial.com is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

Источник

Коды ответов сервера. Ошибки 404, 407, 408, 500, 502, 503 и другие статусы.

Коды ответов сервера или, как их еще называют, коды состояния HTTP (англ. HTTP Status Codes) передаются в заголовке ответа сервера на запрос клиента по протоколу HTTP, и содержат информацию о том, насколько серверу удалось обработать запрос клиента.

Звучит сложновато? На самом деле ничего сложного в этом нет. Смотрите..

Для начала нужно разобраться, что такое клиент и сервер, и, как говорится, зачем они вам. Клиент-серверная архитектура лежит в основе привычного нам интернета. Контент сайтов и приложений находится на серверах, и для доступа к нему используются программы-клиенты, которые умеют взаимодействовать с серверами (они также являются программами) по различным сетевым протоколам (каналам), в частности по протоколу HTTP.

Http code 204. Смотреть фото Http code 204. Смотреть картинку Http code 204. Картинка про Http code 204. Фото Http code 204

Когда какой-либо веб-клиент (браузер или поисковый робот) запрашивает у сервера информацию (страницу, файл или другие данные), сервер пытается выполнить запрос и отдать результат клиенту (ведь клиент всегда прав 😉 Если серверу это удается, он сообщает об этом (в заголовке ответа) и отдает (в теле ответа) то, что нужно клиенту. Но бывает и такое, что сервер не может найти нужный файл/страницу, или он перегружен запросами, или для доступа к контенту нужна авторизация, или еще что-то. Обо всем этом он также должен сообщить клиенту. Клиент и сервер общаются они при помощи кодов. Получив ответ от сервера, клиент должен его обработать согласно коду состояния.

Эти коды стандартизированы и используются всеми серверами и клиентами, которые взаимодействуют при помощи протокола HTTP. Они состоят из 3 цифр, первая из которых указывает на класс (категорию) кода статуса. Существует 5 классов:

Кодов, как вы ведите, очень много, и вам, конечно же, не нужно забивать ими голову. Но некоторые, наиболее часто встречающиеся, полезно знать.

Давайте рассмотрим указанные выше классы с их наиболее распространенными кодами и особенно подробно разберем последние два класса кодов.

1хх Информационные коды

Это коды, при помощи которых сервер информирует клиента о том, что его запрос принят в обработку. При этом, от клиента не требуется никаких дальнейших действий.

100 Continue

Этот код ответа означает, что сервер удовлетворён начальными сведениями о запросе, и клиент может продолжать. Получение такого HTTP кода может потребоваться, если клиенту нужно отправить на сервер большой объем данных (например, через метод POST) и перед отправкой этих данных нужно убедиться, в том, что сервер сможет их принять.

101 Switching Protocols

При помощи HTTP кода 101 сервер предлагает клиенту переключиться на более подходящий для указанного ресурса протокол. Список предлагаемых протоколов передается в заголовке ответа Update.

102 Processing

Код ответа 102 информирует клиента о том, что полученный от него запрос принят в обработку, но для его выполнения потребуется время. Получив такой ответ, клиент должен дожидаться выполнения запроса и не разрывать соединение с сервером (сбросить таймер и ожидать следующего ответа).

2хх Успешное выполнение

Коды этого класса передаются, если запрос от клиента был успешно получен, принят, обработан и выполнен сервером.

200 OK

Код статуса 200 OK является, наверное, самым важным, т.к. он означает, что сервер успешно выполнил то, что от него хотел клиент. Например, если клиент запрашивал определенную страницу, в ответе сервера, вместе с HTTP статусом 200, он также найдет и ее HTML-код. А если в запросе клиента были данные (например, заполненной формы регистрации), которые нужно было обработать, в ответе, помимо кода 200, будет информация о результате обработки.

201 Created

Этот HTTP код сообщает клиенту о том, что в результате его запроса был создан новый ресурс (например, запись в блоге или комментарий). Обычно, этот код передается в ответ на запрос с методом PUT. Кроме кода 201, в ответе сервера также передается ссылка на созданный ресурс.

202 Accepted

Код 202 означает, что запрос принят в обработку, но еще не выполнен, и т.к.его выполнение может занять длительное время, клиенту не обязательно ждать результата. При этом нет гарантии, что запрос будет выполнен, он может быть и отклонен.

203 Non-Authoritative Information

Данный код означает, что сервер понял и принял запрос, но возвращаемая им информация могла устареть или является неактуальной, т.к. взята из другого источника (например, с другого сервера или из резервной копии) и поэтому, полученные данные не стоит воспринимать как авторитетные.

204 No Content

HTTP код 204 означает, что сервер успешно обработал запрос, но в своем ответе не передает каких либо данных, и поэтому клиенту не следует обновлять содержимое документа.

206 Partial Content

Http code 204. Смотреть фото Http code 204. Смотреть картинку Http code 204. Картинка про Http code 204. Фото Http code 204

Этот код сообщает клиенту о том, что сервер передает только часть запрошенного ресурса, т.к. в своем запросе клиент указал диапазон данных (заголовок диапазона (Range Header). Это позволяет докачивать прерванные загрузки или разбивать скачивание на несколько потоков).

3хх Перенаправление

При этом, перейдя по новому адресу, который возвращается в ответе сервера вместе с кодом этого класса, клиент может быть повторно перенаправлен дальше, а потом еще дальше и т.д. Он также может быть перенаправлен и по тому адресу, где уже был и тогда перенаправление зацикливается. Поэтому при множественных перенаправлениях клиенты обычно спрашивают у пользователя разрешение.

300 Multiple Choices

HTTP код 300 означает, что по указанному адресу находятся сразу несколько ресурсов (например, файлы с разным MIME-типом, разные языковые версии страницы, разные форматы видео- или аудио-ресурса), и сервер предлагает клиенту выбрать из списка ресурсов, который также передается в ответе.

301 Moved Permanently

Http code 204. Смотреть фото Http code 204. Смотреть картинку Http code 204. Картинка про Http code 204. Фото Http code 204Если вы переносите проиндексированную поисковиками страницу и не хотите потерять трафик на нее, убедитесь, что по старому адресу возвращается код 301 Moved Permanently. Тогда поисковая система склеит оба адреса.

302 Found (ранее Moved Temporarily)

Код 302 Found используется сервером для сообщения клиенту о том, что запрашиваемый ресурс был (временно) перемещен по новому адресу, где его все-таки удалось найти. Вместе со статусом 302 сервер передает заголовок с новым адресом.

Многие клиенты, в нарушение стандарта, для перехода по новому адресу используют метод GET, даже если в начальном запросе использовался другой метод (POST/PUT/DELETE), что может привести к непредвиденным последствиям. Чтобы этого избежать, следует использовать статусы 303 и 307.

303 See Other

Этот код означает, что сервер успешно обработал запрос клиента, но предлагает ему перейти по другому адресу (также передается в этом ответе), используя метод GET.

Такое можно часто встретить на сайтах, работающих на движке WordPress. Когда вы что-то пишете в поле поиска и нажимаете на клавишу Enter, открывается не список результатов поиска, а наиболее релевантный результат. Происходит примерно следующее: клиент отправляет запрос с поисковой фразой методом POST на сервер, где установлен WP, который выбирает наиболее подходящий результат и возвращает ответ с кодом 303 See Other и адресом выбранной статьи. Получив этот ответ, клиент (браузер) переходит по указанному адресу.

304 Not Modified

Код статуса HTTP 304 Not Modified означает, что хотя запрашиваемый ресурс и был найден по указанному адресу, его версия не отличается от указанной в заголовке запроса (If-Modified-Since), поэтому нет необходимости пересылать его снова.

307 Temporary Redirect

Этот код означает, что запрашиваемый ресурс находится по другому адресу (он тоже передается в ответе), но последующие запросы нужно направлять по старому адресу. В отличие от кода 302, этот статус не позволяет менять метод запроса, т.е. если в первом запросе использовался метод POST, то и в запросе по новому адресу должен использоваться POST.

308 Permanent Redirect

Этот HTTP код, как и код 301 означает, что запрашиваемый ресурс окончательно перенесен на новое место, но в отличие от него, как и 307 код, не позволяет менять метод запроса.

4xx Ошибка на стороне клиента

Данный класс содержит коды, информирующие, что сервер не смог вернуть запрашиваемый ресурс по вине клиента (допущена ошибка в запросе или не выполнены действия, которые должны предшествовать запросу и т.д.) В большинстве случаев вместе с кодом ошибки сервер возвращает пояснение, в котором сказано, что за ошибка произошла, является ли она временной или постоянной. Это пояснение клиент должен вывести пользователю.

Ошибка 400 Bad Request

Что означает 400 Bad Request?

Дословно Bad Request переводится как «плохой запрос». При помощи HTTP кода 400 сервер сообщает клиенту, что не может обработать запрос из-за допущенной в нем синтаксической ошибки.

Не смотря на то, что класс кодов 4хх говорит о том, что ошибка произошла на стороне клиента, часто бывает, что сервер из-за неправильной конфигурации или ошибки в скриптах не может обработать стандартный запрос клиента и выдает ошибку 400.

Как исправить 400 Bad Request?

Ниже описаны некоторые характерные причины ошибки 400 и способы их устранения.

На стороне клиента

На стороне сервера

Ошибка 401 Unauthorized

Что означает HTTP статус 401 Unauthorized?

Unauthorized переводится как «неавторизован». При помощи кода 401 сервер сообщает клиенту, что для доступа к ресурсу требуется авторизация, и клиент должен отправить в следующем запросе заголовок WWW-Authenticate с именем пользователя и паролем. В противном случае, либо если передано неверное имя или пароль, сервер снова вернет ошибку 401.

Http code 204. Смотреть фото Http code 204. Смотреть картинку Http code 204. Картинка про Http code 204. Фото Http code 204

Как исправить 401 Unauthorized?

Если вы пользователь сайта

Если вы владелец сайта

Ошибка 402 Payment Required

Этот HTTP статус пока не получил широкого распространения. Код 402 зарезервирован для использования в будущем. Сейчас его можно встретить, например, при превышении дневного лимита запросов к Google Developers API, ну или в названии одного из эпизодов сериала Mr. Robot 😉

Ошибка 403 Forbidden

Что означает 403 Forbidden?

Дословно Forbidden переводится как «запрещен». Когда сервер возвращает HTTP код 403 Forbidden это значит, что, несмотря на то, что переданный клиентом запрос содержит валидные данные и понятен, сервер все-таки отказывает в его выполнении, и клиенту не следует пытаться повторить этот запрос.

Ошибка 403 может появляться в двух случаях:

Как исправить 403 Forbidden?

Если вы посетитель сайта

Если вы владелец сайта

Ошибка 404 Not Found

Что означает 404 Not Found?

Это наверное самая часто встречающаяся, и потому, самая широко известная ошибка. Дословно Not Found переводится как «не найдено». Когда сервер возвращает HTTP код 404 Not Found это значит, что он не смог найти по указанному адресу запрашиваемый ресурс. При этом сервер как бы не исключает возможности того, что ресурс может появиться снова, поэтому не запрещает клиенту обращаться с данным запросом позже.

Иногда сервер может возвращать статус 404 даже если ресурс найден, но доступ к нему ограничен, так сказать, чтобы никто не догадался.

Как исправить 404 Not Found?

Если вы посетитель сайта

Если вы владелец сайта

Ошибка 405 Method Not Allowed

Дословно Method Not Allowed переводится как «метод не разрешен». При помощи кода 405 сервер сообщает клиенту, о том, что используемый тип HTTP-запроса по данному адресу не поддерживается. Например, клиент передает GET-запрос по адресу, где ожидаются данные формы, отправленные через POST, или клиент пытается обновить доступный только для чтения ресурс через метод PUT.

Ошибка 406 Not Acceptable

Ошибка 407 Proxy Authentication Required

Что означает 407 Proxy Authentication Required?

Дословно Proxy Authentication Required переводится как «требуется авторизация прокси». Если в ответе сервера передается HTTP код 407, это значит, что запрос клиента не может быть выполнен, т.к. отсутствуют данные для авторизации на прокси-сервере, через который производится обмен данными. Этот код по смыслу похож на код 401 Unauthorized (Неавторизован), но в отличие от него, говорит о том, что клиенту нужно авторизоваться не на самом сервере, а на прокси-сервере, который находится между ними.

Как исправить 407 Proxy Authentication Required?

Не смотря на то, что коды класса 4хх свидетельствуют об ошибках на стороне клиента, причиной ошибки 407 Proxy Authentication Required может быть и некорректная настройка основного сервера или прокси-сервера, через который передается запрос. Все же, начать поиски причины этой ошибки следует с клиента.

Если вы посетитель сайта

Если вы владелец сайта

408 Request Timeout

Что означает 408 Request Timeout?

Дословно Request Timeout переводится как «тайм-аут запроса». Если в ответе сервера передается HTTP код 408, это значит, что время ожидания запроса клиента истекло и сервер разрывает соединение. При этом повторные запросы по данному адресу не запрещаются.

Как исправить 408 Request Timeout?

Если вы посетитель сайта

Если вы владелец сайта

Ошибка 409 Conflict

Что означает 409 Conflict?

Дословно Conflict переводится как «Конфликт». Сервер возвращает HTTP код 409 в случае конфликтного обращения к ресурсу, например, когда два клиента пытаются изменить его при помощи метода PUT, либо клиент пытается загрузить на сервер с системой контроля версий файл, который старше уже загруженного.

Http code 204. Смотреть фото Http code 204. Смотреть картинку Http code 204. Картинка про Http code 204. Фото Http code 204

В основном, код 409 отдает не сам сервер, а работающие на нем скрипты (CMS, системы контроля версий и т.д.)

Как исправить 409 Conflict?

Ошибка 410 Gone

HTTP статус 410 Gone означает, что запрашиваемый ресурс удален и больше не будет доступен по данному адресу. Если клиентом является поисковый робот, он должен удалить ресурс из своего индекса.

Ошибка 411 Length Required

Ошибка 412 Precondition Failed

При помощи HTTP кода 412 сервер сообщает, что запрашиваемый ресурс не соответствует требованиям, которые клиент указал в заголовках запроса.

Ошибка 413 Payload Too Large

Данный код информирует о том, что сервер не может обработать запрос, т.к. он слишком большой.

Ошибка 414 URI Too Long

Http code 204. Смотреть фото Http code 204. Смотреть картинку Http code 204. Картинка про Http code 204. Фото Http code 204

HTTP код 414 сообщает клиенту о том, что запрос не может быть обработан из-за слишком длинного URI. Основной причиной ошибки является передача большого объема данных (например, из формы) через метод GET вместо POST.

Ошибка 415 Unsupported Media Type

HTTP код 415 означает, что запрос клиента отклонен т.к. содержит данные, тип которых ресурс не может обработать. Это может случиться, например, при загрузке на сервер файла, формат которого не поддерживается обработчиком загрузки.

Ошибка 416 Range Not Satisfiable

Ошибка 417 Expectation Failed

Ошибка 418 I’m a teapot

Не смотря на то, что статус 418 является шуточным, его поддерживают некоторые популярные фреймворки (например, Django и Symfony). А Google сделал специальную страницу, которая возвращает HTTP код 418 и «наливает чай».

Ошибка 421 Misdirected Request

Этот код означает, что запрос был направлен серверу, который не способен вернуть ответ. HTTP статус 421 может возвращаться сервером, который не настроен на создание ответов для комбинации схемы и полномочий, включенных в URI запроса.

Ошибка 422 Unprocessable Entity

Данный статус свидетельствует о том, хотя запрос был правильно составлен и сервер его принял, он, все же, не может его обработать из-за какой-то семантической ошибки.

Ошибка 423 Locked

Этот код говорит от том, что обращение к ресурсу с использованием указанного в запросе метода заблокировано.

Ошибка 424 Failed Dependency

Ошибка 424 возвращается сервером если выполнение запроса зависит от другого запроса, который не был выполнен.

Ошибка 426 Upgrade Required

При помощи этого кода сервер сообщает клиенту о необходимости переключиться на другой протокол (например, SSL). Вместе со статусом 426 в ответе должен содержаться заголовок Upgrade с указанием нужного протокола.

Ошибка 428 Precondition Required

Ошибка 429 Too Many Requests

Что означает 429 Too Many Requests?

Дословно Too Many Requests переводится как «слишком много запросов». При помощи этого статуса сервер сообщает о том, что в сейчас не принимает запросы от данного клиента, т.к. за короткий промежуток времени их от него поступает слишком много. Вместе с кодом 429 сервер также передает заголовок Retry-After с указанием количества секунд, через которое клиент может повторить запрос.

Http code 204. Смотреть фото Http code 204. Смотреть картинку Http code 204. Картинка про Http code 204. Фото Http code 204

Как исправить 429 Too Many Requests?

Ошибка 431 Request Header Fields Too Large

Http code 204. Смотреть фото Http code 204. Смотреть картинку Http code 204. Картинка про Http code 204. Фото Http code 204

Ошибка 451 Unavailable For Legal Reasons

Этот код означает, что сервер блокирует доступ к ресурсу или набору ресурсов в связи с требованием закона. Код 451 является отсылкой к роману Рэя Брэдбери «451 градус по Фаренгейту», в котором описывает общество, где книги находятся под запретом.

5xx Ошибка на стороне сервера

В этот класс включены коды описывающие случаи, когда сервер знает, что совершил ошибку или не способен по каким-либо причинам выполнить запрос. Помимо кода ошибки, ответ сервера должен включать уточнение обстоятельств ее возникновения, а также информировать о том, является ли ситуация временной или постоянной (это касается всех методов, кроме HEAD). В свою очередь, клиент должен вывести эту информацию пользователю.

Ошибка 500 Internal Server Error

Что означает 500 Internal Server Error?

Дословно Internal Server Error переводится как «Внутренняя ошибка сервера». Ошибка 500 является дефолтной и возвращается, когда более специфичные статусы не подходят. Поэтому найти ее причину довольно сложно. Это может быть как синтаксическая ошибка в коде скрипта-обработчика, так и ошибка диска или отсутствие какого-либо программного модуля, а также еще много всего.

Как исправить 500 Internal Server Error?

Если вы посетитель сайта

Так как 500 это серверная ошибка, вы мало что можете сделать. Все же можно попробовать следующее:

Если вы владелец сайта

Ошибка 501 Not Implemented

При помощи HTTP кода 501 сервер сообщает о том, что механизм необходимый для выполнения запроса на нем пока не реализован. Эта ошибка обычно возникает, когда сервер не может обработать запрос указанным в нем методом.

Ошибка 502 Bad Gateway

Что означает 502 Bad Gateway?

Bad Gateway переводится на русский язык как «Неверный шлюз». Если в ответ на свой запрос клиент получает HTTP код 502, это значит, что сервер, к которому он обратился, выступает в роли прокси и, в свою очередь, получил неверный ответ от вышестоящего сервера.

Http code 204. Смотреть фото Http code 204. Смотреть картинку Http code 204. Картинка про Http code 204. Фото Http code 204

Причин возникновения данной ошибки может быть несколько. Вот несколько наиболее вероятных:

Как исправить 502 Bad Gateway?

Если вы посетитель сайта

Если вы владелец сайта

Ошибка 503 Service Unavailable

Что означает 503 Service Unavailable?

Service Unavailable переводится на русский как «Сервис не доступен». HTTP статус 503 означает, что сервер не может обработать запрос т.к. в данный момент он перегружен запросами или находится на обслуживании (например, на нем идет обновление программного обеспечения).

Как исправить 503 Service Unavailable?

Если вы посетитель сайта

Если вы владелец сайта

Ошибка 504 Gateway Timeout

HTTP код 504 означает, что сервер, к которому обращается клиент, является шлюзом или прокси и он не смог выполнить запрос т.к. не дождался ответа от вышестоящего сервера.

Эта ошибка возникает в процессе взаимодействия серверов, поэтому вы, как посетитель сайта, вряд ли можете что-то сделать. Если вы столкнулись с ошибкой 504, пытаясь открыть какую-то страницу, попробуйте просто обновить ее при помощи Ctrl + F5 или зайти немного позже. Скорее всего, эта ошибка временная и возникла по причине того, что вышестоящий сервер в данный момент перегружен запросами, поэтому ваш прокси-сервер не может получить от него ответ в отведенные для этого рамки и разрывает соединение.

505 HTTP Version Not Supported

Код ответа 505 означает, что версия HTTP, указанная в запросе, сервером не поддерживается.

507 Insufficient Storage

Данный HTTP код сообщает клиенту о том, что на сервере не хватает места для выполнения запроса. Этот статус, в основном, используется для WebDAV клиентов, но может также заменять 413 Payload Too Large.

508 Loop Detected

Этот код свидетельствует о том, что сервер обнаружил бесконечный цикл, пытаясь обработать запрос.

В этой статье мы рассмотрели некоторые основные официальные коды ответов сервера, которые описаны в рабочих предложениях (RFC). Кроме них есть и неофициальные HTTP коды, специфичные для определенных программных продуктов и приложений (Apache, nginx, Cloudflare, AWS и др.). О них я расскажу в одной из следующих статей.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *