Why We Need to Set Content Type of header request

Usman Hafeez picture Usman Hafeez · Feb 27, 2017 · Viewed 8.2k times · Source

I want to know that what is content type, why we need to set content type of header request and how many types of header content can be set? please provide documentation if possible.

Answer

bramwelt picture bramwelt · Feb 27, 2017

Content-Type in the header of a HTTP request specifies to the server what data it should expect. If a server allows and accepts multiple types of content it can use this field know how to interpret the body of the request.

For example: If a server allows both XML and JSON data at the same endpoint, then setting the Content-Type as:

Content-Type: application/json

would let the server know it should expect the request body to contain JSON. Whereas passing:

Content-Type: text/xml

would inform the server to expect XML in the body.

RFC7321 - Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content defines Content-Type in section 3.1.1.5:

The "Content-Type" header field indicates the media type of the associated representation: either the representation enclosed in the message payload or the selected representation, as determined by the message semantics. The indicated media type defines both the data format and how that data is intended to be processed by a recipient, within the scope of the received message semantics, after any content codings indicated by Content-Encoding are decoded.

There are 1500+ Media types registered with the IANA which can be set as the Content-Type for a request.

The last paragraph of section 3.1.1.5 explains that if Content-Type is not set, the server may assume the data is application/octet-stream or interpret the request any way it wants. But:

Clients that do so risk drawing incorrect conclusions, which might expose additional security risks (e.g., "privilege escalation").

It is called Content Sniffing when a server does this and may be disabled by setting:

X-Content-Type-Options: nosniff