Mike
Mike

Reputation: 25

Play Framework 2.x always send single response code

Hopefully you guys can help me with this! I have a problem where I need to send a constant response code no matter what the request contains. If the request has bad JSON etc. The response I need to send is a 204 (No Content)

Here's my code where I try to send back a no content header.

    public Result response(){
    RequestBody body = request().body();
        System.out.println(body.asJson());
        return noContent();
    }

Now if I try and send a request containing JSON like below. It returns a 400 (Bad request). I want to send a 204 no matter what. Please let me know what you guys come up with.

JSON POST
{
   "mike":"mike
}

Thanks

Edit:

Sorry I replaced one of these lines of code and forgot to update this. Above I only return 204's, but if my client sends me bad JSON then I still return a 400.

Upvotes: 1

Views: 444

Answers (3)

Mark
Mark

Reputation: 863

You need to modify the global settings for play. Create a class that extends Global Settings and override whichever method you want.

public class Global extends GlobalSettings {
@Override
    public Promise<Result> onBadRequest(RequestHeader arg0, String arg1) {
         super.onBadRequest(arg0, arg1);
        return F.Promise.promise(()->{return play.mvc.Results.noContent();});
    }
}

For more information : https://www.playframework.com/documentation/2.4.x/JavaGlobal

Upvotes: 1

Sivakumar
Sivakumar

Reputation: 1751

Try this,

@BodyParser.Of(BodyParser.Json.class)
public static Result response() {
    JsonNode json = request().body().asJson();

    if(json == null){
        return noContent();
    }else{
        // Get json content from request and process rest..
    }
    return ok("");
}

By using above approach, a 204 HTTP response will be automatically returned for non JSON requests.

Upvotes: 0

Karim BENHDECH
Karim BENHDECH

Reputation: 381

To return 204, you can use noContent method

For that replace ok() by noContent()

Upvotes: 0

Related Questions