I am facing problem with play framework where sending application/json
in content-type header returns a BadRequest
. I have a controller POST method that needs a few headers for the server to calculate the right hmac value, one of the headers is content-type When I send application/json
as the content-type
I get a Badrequest , it works for application\\/json
, but the problem is I need to have application/json to compute the correct hmac value.
I have tried with Curl, Poster and a Java client and I am facing the same issue everywhere, I have a test case written in Scala which sends application/json which works(but that is running against a MockController and a FakeRequest).
Adding Some code
This is how I am adding the content-type header httpPost.addHeader(HttpHeaders.CONTENT_TYPE, "\\"application/json\\"");
or httpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application\\/json");
either of the two work but plain application/json doesn't
This is the controller Method I am calling
def test() = Action {
implicit request =>
Ok("yippiie")
}
Also I tried both with a valid json body and an empty json , got BadRequest in both scenarios with application/json as the content-type header.
Without seeing your code it's hard to be sure (you've got Java in the title, but tagged the question with Scala), but I suspect the problem here is that you are not supplying a valid JSON body with the POST request.
If you use the plain Action {...}
form for the controller action then Play will automatically try to parse the body with the anyContent
BodyParser
, which uses the content-type header to infer the format. This means that if your content-type is application/json
then you must have a valid JSON body (nothing, or an empty string will not suffice.)
For example, with this action code:
def test = Action {
Ok("hello, world\n")
}
... calling it with an invalid JSON body (no data) will fail:
curl -X POST -H "Content-Type: application/json" http://localhost:9000/test
< HTTP/1.1 400 Bad Request
whereas supplying a valid JSON body (an empty object) will succeed:
curl -d "{}" -X POST -H "Content-Type: application/json" http://localhost:9000/test
< hello, world
The reason those other forms of application/json
are "working" is because as far as the application is concerned they're just a random string, meaning Play defaults to parsing as an empty set of URL encoded values, and the action therefore succeeds.
If for some reason you do want to use application/json
as a content type but want to have an empty body, you can use the parse.empty
body parser. If you've definitely got a valid JSON body it's probably best to be explicit about it and use parse.json
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.