Communicating between Play 1.1 server and Play 2.1 server using RESTful API
POST (Sending Play 1.1 Controller)
public static void create (String body) {
WS.WSRequest req = WS.url(PLAY_2.1_SERVER_BASE_URL + "/createUser");
req.authenticate(USER_NAME, PASSWORD);
JsonObject jsonObj = new JsonParser().parse(body).getAsJsonObject();
req.body(jsonObj);
req.headers.put("Content-Type","application/json");
WS.HttpResponse res = req.post();
JsonElement json = res.getJson();
renderJSON(json);
}
POST (Receiving Play 2.1 Controller)
@BodyParser.Of(BodyParser.Json.class)
public static Result createUser() {
Http.Request request = request();
JsonNode json = request.body().asJson();
if (json == null) {
return badRequest("Expecting Json data.");
} else {
User details = Json.fromJson(json,
User.class);
if (details == null) {
return badRequest("Unable to parse json: " + json
+ " into User Details.");
} else {
// Validate the Users Inputs coming from UI
String validationError = validateUserInput(details).toString();
if (validationError.isEmpty()) {
details.setUpdateDate(System.currentTimeMillis());
Key key = details.save();
return Results.ok();
} else {
return badRequest(validationError);
}
}
}
}
POST (Sending Play 1.1 Controller)
public static void create (String body) {
WS.WSRequest req = WS.url(PLAY_2.1_SERVER_BASE_URL + "/createUser");
req.authenticate(USER_NAME, PASSWORD);
JsonObject jsonObj = new JsonParser().parse(body).getAsJsonObject();
req.body(jsonObj);
req.headers.put("Content-Type","application/json");
WS.HttpResponse res = req.post();
JsonElement json = res.getJson();
renderJSON(json);
}
POST (Receiving Play 2.1 Controller)
@BodyParser.Of(BodyParser.Json.class)
public static Result createUser() {
Http.Request request = request();
JsonNode json = request.body().asJson();
if (json == null) {
return badRequest("Expecting Json data.");
} else {
User details = Json.fromJson(json,
User.class);
if (details == null) {
return badRequest("Unable to parse json: " + json
+ " into User Details.");
} else {
// Validate the Users Inputs coming from UI
String validationError = validateUserInput(details).toString();
if (validationError.isEmpty()) {
details.setUpdateDate(System.currentTimeMillis());
Key key = details.save();
return Results.ok();
} else {
return badRequest(validationError);
}
}
}
}
1 comment:
this tool will also help to understand JSON http://codebeautify.org/jsonviewer and http://jsonformatter.org
Post a Comment