interceptorplayframework-2.3

How to Modify response Result Body in Interceptor Play framework 2.3.8?


 @Override
public Promise<Result> call(Http.Context ctx) throws java.lang.Throwable {
     Promise<Result> result = this.delegate.call(ctx);
     Http.Response response = ctx.response();
     response.setHeader("Access-Control-Allow-Origin", "*");
     return result.map(r -> {
        play.api.mvc.Result res =  r.toScala();
        final int status = r.toScala().header().status();
        if(status == 200 || status == 201) {
            String responseBody = new String(JavaResultExtractor.getBody(r, 0L));
            final Map<String,String> headers =  JavaResultExtractor.getHeaders(r);
            ResponseHeader responseHeader = res.header();
            return new Result(responseHeader, res.body());
        }
        return r;
     });
}

I would like to modify the body of response on interceptor ?. I can able to get the result body. So that I will modify the response. How to override the existing body response and result as Result.


Solution

  • Did the body content update like this.

     

    return result.map(r -> {
                    final int status = r.toScala().header().status();
                    if(status == 200 || status == 201) {
                        // Can change the body content here
                        Status s = status(status,new String(JavaResultExtractor.getBody(r, 0L)));
                        return s.as(JavaResultExtractor.getHeaders(r).get("Content-Type"));
                    }
                    return r;
                 });