Clint
Clint

Reputation: 201

Modifying HTTP response body and message

I need to be able to modify the HTTP response body of the response that I am getting when someone hits my Service API. I tried using ConatinerResponseFilter to modify the body, but I believe it will only modify the headers and not the response body. Can someone tell me how I can modify the HTTP response body ,message and the status?

Upvotes: 0

Views: 3569

Answers (2)

cassiomolin
cassiomolin

Reputation: 130837

It could be achieved with a WriterInterceptor:

@Provider
public class CustomWriterInterceptor implements WriterInterceptor {

    @Override
    public void aroundWriteTo(WriterInterceptorContext context) 
                throws IOException, WebApplicationException {

        OutputStream outputStream = context.getOutputStream();

        // Manipulate the HTTP entity using the OutputStream

        context.setOutputStream(outputStream);
        context.proceed();
    }
}

In this answer you will find an example of how to modify a JSON sent in the request payload using Jackson (the same idea can be used to manipulate response payload).

Upvotes: 2

Aravind R
Aravind R

Reputation: 766

The trick is to use a wrapper because body when read as a stream becomes in accessible

Modify HttpServletRequest body

Check this or just check online for modify body in filter

Note :if u are doing a web service then using frameworks like CXF makes it easy modify

Upvotes: 0

Related Questions