Play Framework 2.x 始终发送单一响应代码
Play Framework 2.x always send single response code
希望你们能帮我解决这个问题!我有一个问题,无论请求包含什么,我都需要发送一个恒定的响应代码。如果请求有错误 JSON 等。我需要发送的响应是 204(无内容)
这是我的代码,我在其中尝试发回无内容 header。
public Result response(){
RequestBody body = request().body();
System.out.println(body.asJson());
return noContent();
}
现在,如果我尝试发送包含 JSON 的请求,如下所示。它 return 是一个 400(错误的请求)。无论如何,我都想发送 204。请告诉我你们的想法。
JSON POST
{
"mike":"mike
}
谢谢
编辑:
抱歉,我替换了其中一行代码,但忘记更新了。上面我只有 return 204 的,但是如果我的客户给我发送错误 JSON 那么我仍然 return 一个 400。
试试这个,
@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("");
}
通过使用上述方法,对于非 JSON 请求,将自动返回 204 HTTP 响应。
到return204,可以使用noContent方法
为此,将 ok()
替换为 noContent()
您需要修改全局设置才能播放。
创建一个扩展全局设置的 class 并覆盖您想要的任何方法。
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();});
}
}
更多信息:https://www.playframework.com/documentation/2.4.x/JavaGlobal
希望你们能帮我解决这个问题!我有一个问题,无论请求包含什么,我都需要发送一个恒定的响应代码。如果请求有错误 JSON 等。我需要发送的响应是 204(无内容)
这是我的代码,我在其中尝试发回无内容 header。
public Result response(){
RequestBody body = request().body();
System.out.println(body.asJson());
return noContent();
}
现在,如果我尝试发送包含 JSON 的请求,如下所示。它 return 是一个 400(错误的请求)。无论如何,我都想发送 204。请告诉我你们的想法。
JSON POST
{
"mike":"mike
}
谢谢
编辑:
抱歉,我替换了其中一行代码,但忘记更新了。上面我只有 return 204 的,但是如果我的客户给我发送错误 JSON 那么我仍然 return 一个 400。
试试这个,
@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("");
}
通过使用上述方法,对于非 JSON 请求,将自动返回 204 HTTP 响应。
到return204,可以使用noContent方法
为此,将 ok()
替换为 noContent()
您需要修改全局设置才能播放。 创建一个扩展全局设置的 class 并覆盖您想要的任何方法。
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();});
}
}
更多信息:https://www.playframework.com/documentation/2.4.x/JavaGlobal