Mandar Naik Mandar Naik - 8 months ago 51
AngularJS Question

How to parse Response from WebService call in Play 2.3.x

Background : I'm calling backend WebServices from

Play controller
and sending the
Response
(in JSON format) to AngularJS module wrapped in
play.mvc.Result
. This integration works seamlessly.

Problem Statement : Now I want to parse the
Response
and use it for some business logic; but
play.mvc.Result
class has only one method which is
toScala()
. How do I get the body of
play.mvc.Result
.
Can I use
play.libs.F.Promise
to get my job done?

Below is the Generalized code which takes JSON request body and Service URL as parameter and returns the
play.mvc.Result
.

WSRequestHolder requestHolder = WS.url("https://application.url/ws/endpoint")
.setHeader("Content-Type", "application/json");
final Promise<String> promise = requestHolder.post(jsonRequest)
.map(new Function<WS.Response, String>() {
@Override
public String apply(final Response a) throws Throwable {
//Do i need to Parse from here???
return a.getBody();
}
});

return Results.async(promise.map(new Function<String, Result>() {
@Override
public Result apply(final String a) throws Throwable {
if(STR_UNAUTHORIZED.equals(a)){
return Results.redirect(controllers.routes.Authentication.login("",""));
}
return Results.ok(a);
}
}));


So is there a way to extract the
Response
body from
play.mvc.Result
or is there any alternate way to do this?

Answer Source

Below code would Parse the response from WebService call in synchronized way:

WSRequestHolder requestHolder = WS.url("https://application.url/ws/endpoint")
            .setHeader("Content-Type", "application/json");
final Promise<WS.Response> promise = requestHolder.get();
Response myResponse=promise.get(50000); 
// This code returns the Parsed response in form of String
return myResponse.getBody();