Should Content-Type header be present when the message body is empty?
Asked Answered
T

1

77

Should the Content-Type header be present in an HTTP request or response when there is no payload body?

Is the correct combination of HTTP headers in this case to have no Content-Type and a Content-Length of 0, or should the Content-Type not be present at all when the message lacks a body?

Terryn answered 21/4, 2015 at 22:36 Comment(3)
possible duplicate of What should the Content-Type be for a 4xx error without a body?Steatite
@RobinGreen: This question is more general and the answer quotes RFC, so it's better to keep this question and and close the other one.Daffodil
Possible duplicate of What Content-Type should a 204 No Response use?Tarn
J
63

RFC 7231 says:

A sender that generates a message containing a payload body SHOULD generate a Content-Type header field in that message [...]

So it doesn't say explicitly what to do if you're generating a message that doesn't have a payload body, but it certainly seems implied that not sending a Content-Type header would be appropriate in that case.

Content-Length: 0 is how you would indicate to the receiver that there will be no body, unless you're using something like chunked encoding.

Jealous answered 21/4, 2015 at 22:57 Comment(2)
Using RestEasy 3.15.4, I have the error javax.ws.rs.NotSupportedException: RESTEASY003065: Cannot consume content type when doing a POST without body, with header Content-Length: 0 and without Content-Type header. Adding Content-Type: application/json solved the problem. When the error occured, the server returns chunked response. That's strange because it was occuring only with my application, but when I did the same call with Postman, there was no error. Anyway, it's maybe safer to add a dummy content type because not all server-side implementation would understand that.Repentance
All "nothings" aren't equal. Take any typed language that supports the concept of null for example. A Foo x = null is not the same as Bar y = null. Similarly, an empty application/json response is not the same an empty image/png response. An empty JSON response would be interpreted as null, whereas an empty PNG is an error.Burnejones

© 2022 - 2024 — McMap. All rights reserved.