Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract result content from play.mvc.Result object in play application?

actually I am doing redirect from one play application to another play application, finally I receive response as Result object.. Below is the action in two applications. I am redirecting from apllication1 to application2. Application 2 will return JSON string, that I need to extract.

How can I retrieve JSON content from Result object?

Application1:

public static Result redirectTest(){

    Result result =  redirect("http://ipaddress:9000/authenticate");
    /*** here I would like to extract JSON string from result***/
    return result;
}

Application2:

@SecuredAction
public static Result index() {
     Map<String, String> response = new HashMap<String, String>();
     DemoUser user = (DemoUser) ctx().args.get(SecureSocial.USER_KEY);

       for(BasicProfile basicProfile: user.identities){
           response.put("name", basicProfile.firstName().get());
           response.put("emailId", basicProfile.email().get());
           response.put("providerId", basicProfile.providerId());
           response.put("avatarurl", basicProfile.avatarUrl().get());
       }

    return ok(new JSONObject(response).toString());
}
like image 753
Jayaprakash Narayanan Avatar asked Dec 15 '22 19:12

Jayaprakash Narayanan


2 Answers

I think play.test.Helpers.contentAsString is what you're looking for.

public static java.lang.String contentAsString(Result result)

Extracts the content as String.

Still available in Play 2.8.x.

like image 139
Alex Avatar answered May 18 '23 14:05

Alex


Use JavaResultExtractor, example:

Result result = ...;
byte[] body = JavaResultExtractor.getBody(result, 0L);

Having a byte array, you can extract charset from Content-Type header and create java.lang.String:

String header = JavaResultExtractor.getHeaders(result).get("Content-Type");
String charset = "utf-8";
if(header != null && header.contains("; charset=")){
    charset = header.substring(header.indexOf("; charset=") + 10, header.length()).trim();
}
String bodyStr = new String(body, charset);
JsonNode bodyJson = Json.parse(bodyStr);

Some of above code was copied from play.test.Helpers

like image 24
Mon Calamari Avatar answered May 18 '23 14:05

Mon Calamari