#JSON请求的处理和服务
1.处理Json请求
Json请求是使用有效Json数据作为Http请求的请求体的。它的Content-type头必须指定为"text/json"或者"application/json"MIME类型。
默认的,一个动作使用any content 体解析器,你可以把请求(响应)体以Json格式取回来。
public static index sayHello() {
JsonNode json = request().body().asJson();
if(json == null) {
return badRequest("Expecting Json data");
} else {
String name = json.findPath("name").getTextValue();
if(name == null) {
return badRequest("Missing parameter [name]");
} else {
return ok("Hello " + name);
}
}
}
当然了,指定我们自己的BodyParser来让Play把内容体直接解析为Json是更好的方式:
@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响应会被自动返回。
你可以在命令行下用curl命令测试:
curl
--header "Content-type: application/json"
--request POST
--data '{"name": "Guillaume"}'
http://localhost:9000/sayHello
它返回:
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 15
Hello Guillaume
2.Json响应的服务
在以前的例子中我们处理Json请求,但是返回一个"text/plain"的响应。现在我们来发送会一个有效的JsonHttp响应:
@BodyParser.Of(Json.class)
public static index sayHello() {
ObjectNode result = Json.newObject();
String name = json.findPath("name").getTextValue();
if(name == null) {
result.put("status", "KO");
result.put("message", "Missing parameter [name]");
return badRequest(result);
} else {
result.put("status", "OK");
result.put("message", "Hello " + name);
return ok(result);
}
}
现在它的响应是:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 43
{"status":"OK","message":"Hello Guillaume"}