我正在使用 Play 创建 RESTful 服务。我希望 Play 拒绝请求 header 中未将媒体类型指定为 JSON 的任何请求。
教程中有一个很好的例子。 http://www.playframework.com/documentation/2.0/JavaJsonRequests
阅读其中所说的...
@BodyParser.Of(Json.class)
public static index sayHello() {
String name = json.findPath("name").getTextValue();
if(name == null) {
return badRequest("Missing parameter [name]");
} else {
return ok("Hello " + name);
}
}
注意:这样,对于非 JSON 请求将自动返回 400 HTTP 响应。
为什么它返回 HTTP 错误 400(错误请求),而不是 HTTP 错误 415(不支持的媒体类型)?
有办法改变这种行为吗?
最佳答案
您可以使用 status(int, String) 方法返回自定义 HTTP 响应:
return status(415, "The only supported content type is application/json");
关于java - Play Framework : Returning 400 instead of 415,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19204969/