简体   繁体   中英

Jersey REST response message body

How to print response message body as a String within filter method and tried couple of response methods (getEntityOutputStream() / getEntity() / GetContainerResponseWriter() )

public class Test implements ContainerRequestFilter , ContainerResponseFilter) { 

    @Override 
    public ContainerResponse filter(ContainerRequest request, ContainerResponse response) { 
        response. 
    } 
}

I use the Jersey logging to print out request / response body

in my ResourceConfig

registerInstances(new LoggingFilter(myLogger, true));

LoggingFilter

public class LoggingFilter implements ContainerRequestFilter,  ClientRequestFilter, ContainerResponseFilter,
    ClientResponseFilter, WriterInterceptor {
...

you can check out how they do it : https://github.com/jersey/jersey/blob/master/core-common/src/main/java/org/glassfish/jersey/filter/LoggingFilter.java

I had the same problem and this is what I ended up doing. Basically I return the JSON representation of my entity if I could cast it, else I create a custom response message.

I'm sure there will be better ways to do it.

private String createLoggingResponse(ContainerResponseContext resp) {

    Object entity = resp.getEntity();

    if (BaseModel.class.isInstance(entity)) {
        BaseModel model = (BaseModel) entity;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        model.toJson(out);
        return new String(out.toByteArray());

    } else {

        MediaType mediaType = resp.getMediaType();

        return "[" + entity.toString() + "," + resp.getStatusInfo().getStatusCode() + "," + resp.getStatusInfo().getReasonPhrase() + "," + mediaType.toString() + "]";
    }

}

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