简体   繁体   English

如何在Play 2.3.x中解析来自WebService调用的响应

[英]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 . 背景:我从Play controller调用后端Web服务,并将Response (以JSON格式)发送到包含在play.mvc.Result AngularJS模块。 This integration works seamlessly. 这种集成无缝地工作。

Problem Statement : Now I want to parse the Response and use it for some business logic; 问题陈述:现在我想解析Response并将其用于某些业务逻辑; but play.mvc.Result class has only one method which is toScala() . play.mvc.Result类只有一个方法是toScala() How do I get the body of play.mvc.Result . 我如何获得play.mvc.Result的主体 Can I use play.libs.F.Promise to get my job done? 我可以使用play.libs.F.Promise来完成我的工作吗?

Below is the Generalized code which takes JSON request body and Service URL as parameter and returns the play.mvc.Result . 下面是广义代码,它将JSON请求体和服务URL作为参数并返回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? 那么有没有办法从play.mvc.Result提取Response主体,还是有其他方法可以做到这一点?

Below code would Parse the response from WebService call in synchronized way: 下面的代码将以同步方式解析来自WebService调用的响应:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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