Why is it necessary to specify MIME type here?
Because otherwise web-browsers and other software won't know if the arbitrary stream of bytes they receive from your server is meant to be HTML or plaintext, for example.
What will happen if we don't specify it?
Then you force client applications to guess what the content is supposed to be - and with any guesses (even educated-guesses based on content-sniffing and heuristics) there's a strong probability of something going wrong.
In which cases it can be and can't be omitted?
As far as you're concerned (I assume you're a web application developer) then it should never be omitted: you should always specify it.
Rule-of-thumb: Always specify an explicit (and correct) Content-Type
for your HTTP responses. If you don't know what the correct type is then fallback to using application/octet-stream
, which tells the client that you don't know what it is either - at least that's being honest - and honesty is something we as a society value.
More specifically: the HTTP/1.1 spec does state the Content-Type
header is optional, but honestly, in the 25+ years since HTTP/1.1 we've learned we should always send it. The only time it's okay to omit it is when there is no content (e.g. HTTP 204 No Content
or Content-Length: 0
).