- HTTP-заголовки для описания контента
- Заголовки «Content-Type» и «Content-Disposition»
- HTTP-заголовки запроса «Accept»
- Похожие записи
- Content-Type
- Синтаксис
- Директивы
- Примеры
- Content-Type в HTML формах
- Спецификации
- Совместимость с браузерами
- Смотрите также
- Found a content problem with this page?
- What is a Content Type?
- Headers
- Media Types
HTTP-заголовки для описания контента
Список часто используемых HTTP-заголовков, описывающих содержимое тела HTTP-сообщения с пояснениями.
Content-Length — размер контента в байтах.
Content-Encoding — способ или способы дополнительного кодирования для сжатия контента.
Content-Encoding: gzip Content-Encoding: gzip, br, compress, deflate, identity
Content-Language — язык или языки содержимого.
Content-Language: ru Content-Language: en-US Content-Language: en, ru
Content-Range — диапазон части контента в байтах.
Content-Range: bytes 317990672-635981344/953972016
Заголовки «Content-Type» и «Content-Disposition»
Content-Type — медиа тип и способ передачи контента.
Content-Type: text/plain; charset=UTF-8
- MIME-type/MIME-subtype —медиа тип ( text/plain );
- charset — кодировка контента ( UTF-8 );
- boundary — разделитель для контента, состоящего из разных частей, но отправляемый одним HTTP-сообщением, не должен превышать 70 символов и заканчиваться пробельным символом ( ufU9jd8h ).
Кроме boundary для составного запроса используется заголовок Content-Disposition , применяемый с типом multipart/form-data .
POST /handler HTTP/1.1 Host: example.com Content-Type: multipart/form-data; boundary=ufU9jd8h Content-Length: 849237 --ufU9jd8h Content-Disposition: form-data; name="username" Devanych --ufU9jd8h Content-Disposition: form-data; name="image"; filename="image.png" Content-Type: image/png --ufU9jd8h--
По-мимо отправки составных запросов, Content-Disposition используется для скачивания файлов ( attachment ) и показа контента ( inline ) в браузере.
Content-Disposition: inline Content-Disposition: attachment Content-Disposition: attachment; filename="image.png"
Вместе c Content-Type сервер может отправить заголовок X-Content-Type-Options со значением nosniff , который является подтверждением того, что обязателено нужно использовать медиа тип, переданный в Content-Type .
X-Content-Type-Options: nosniff
HTTP-заголовки запроса «Accept»
Заголовки, отправляемые клиентом. Для всех Accept заголовков при перечислении можно использовать вес/приоритет ( ;q=XXX ), в порядке которого будет происходить выбор праметра для контента ( text/plain;q=0.9 ). Если же вес не указан, то по умолчанию он равняется 1.0 .
Accept — список поддерживаемых или ожидаемых клиентом медиа типов.
- MIME-type/MIME-subtype — конкретный медиа тип ( text/plain );
- MIME-type/* — общий медиа тип без подтипа ( image/* );
- */* — соответствует любому медиа типу.
Accept: text/plain Accept: text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8
Accept-Charset — список поддерживаемых или ожидаемых клиентом кодировок.
Accept-Charset: utf-8 Accept-Charset: utf-8, cp-1251;q=0.9
Accept-Encoding — список поддерживаемых или ожидаемых клиентом способов дополнительного кодирования для сжатия контента.
Accept-Encoding: * Accept-Encoding: gzip Accept-Encoding: gzip, br;q=0.9, compress;q=0.8, deflate;q=0.7, identity;q=0.6, *;q=0.5
Accept-Language — список поддерживаемых или ожидаемых клиентом языков.
Accept-Language: * Accept-Language: ru Accept-Language: en-US, en-GB;q=0.9 Accept-Language: ru, en;q=0.9, *;q=0.8
Похожие записи
Content-Type
Заголовок-сущность Content-Type используется для того, чтобы определить MIME тип ресурса.
В ответах сервера заголовок Content-Type сообщает клиенту, какой будет тип передаваемого контента. В некоторых случаях браузеры пытаются сами определить MIME тип передаваемого контента, но их реакция может быть неадекватной. Чтобы предотвратить такие ситуации, вы можете установить в заголовке X-Content-Type-Options значение nosniff .
В запросах (таких, как POST или PUT ), клиент сообщает серверу тип отправляемых данных.
Тип заголовка | Entity header |
---|---|
Forbidden header name | нет |
CORS-safelisted response-header | да |
Синтаксис
Content-Type: text/html; charset=utf-8 Content-Type: multipart/form-data; boundary=something
Директивы
Директива boundary обязательна для составных сущностей. Она содержит от 1 до 70 символов (не должна заканчиваться пробелом), которые без искажений пройдут через шлюзы email и служит для корректной инкапсуляции всех частей составной сущности.
Примеры
Content-Type в HTML формах
В POST запросе, сгенерированном в результате отправки HTML формы, Content-Type запроса определяется в атрибуте enctype тега .
form action="/" method="post" enctype="multipart/form-data"> input type="text" name="description" value="some text"> input type="file" name="myFile"> button type="submit">Submitbutton> form>
Запрос в этом случае может выглядеть так (менее интересные заголовки опущены):
POST /foo HTTP/1.1 Content-Length: 68137 Content-Type: multipart/form-data; boundary=---------------------------974767299852498929531610575 -----------------------------974767299852498929531610575 Content-Disposition: form-data; name="description" some text -----------------------------974767299852498929531610575 Content-Disposition: form-data; name="myFile"; filename="foo.txt" Content-Type: text/plain (content of the uploaded file foo.txt) -----------------------------974767299852498929531610575--
Спецификации
Спецификация | Заголовок |
---|---|
RFC 7233, секция 4.1: Content-Type in multipart | Hypertext Transfer Protocol (HTTP/1.1): Range Requests |
RFC 7231, секция 3.1.1.5: Content-Type | Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content |
Совместимость с браузерами
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 26 окт. 2022 г. by MDN contributors.
Your blueprint for a better internet.
What is a Content Type?
Content types also known as MIME type or media types are a two part identifier for file formats. The HTTP header Content-Type is responsible for telling the HTTP client or server what type of data is being sent.
Headers
Two main headers are involved when it comes to content types
- Accept — When a HTTP client requests data from a server it can send a comma separated list of media types. For example the headers value could be text/html, text/plain. This hints to the server what the client is looking for. Basically the client is asking the server to respond with text/html and if it cannot handle that try responding with text/plain. Whether or not the server can handle or will honor this is up to the server.
- Content-Type — The content type header tells the client or server what format the data is being transferred in. If the client asked for text/html and the server handled it properly the data should come back with the Content-Type: text/html header. This header is how your browser knows when to render the html vs just displaying raw text. This is also used for images / files.
$ curl -v http://www.google.com * Rebuilt URL to: http://www.google.com/ * Trying 172.217.1.68. * Connected to www.google.com (172.217.1.68) port 80 (#0) > GET / HTTP/1.1 > Host: www.google.com > User-Agent: curl/7.49.1 > Accept: */* > < HTTP/1.1 200 OK < Date: Tue, 10 Jan 2017 02:42:41 GMT < Expires: -1 < Cache-Control: private, max-age=0 < Content-Type: text/html; charset=ISO-8859-1
Notice the Accept: */*, This means accept any format. The Content-Type: text/html header tells the client the server responded with HTML.
Media Types
- text/plain - Simple Raw text
- text/html - Standard HTML, when a browser gets this media type it knows to render the page as HTML instead of raw text. This includes fetching external files such as javascript, css, and images.
- application/octet-stream - A binary file format often used to download files. If a browser gets this media type it automatically downloads the file instead of trying to display / render it.
- application/json - The JSON data format.
- application/pdf - PDF file.
- image/[png,jpeg,gif] - Standard image formats.
These are only some of the formats. As you can see the difference between rendering html vs showing raw text vs downloading a file is all controlled with a simple header. Handling content types with Undertow