简体   繁体   中英

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM