3

I am using Jersey Client to make a REST service call. Now when I receive the response I want to log the json response and I also want to get the entity populated in my response bean.

Client client = Client.create(config);
ClientResponse cr = client
                    .resource(endPoint)
                    .accept("application/json")
                    .get(ClientResponse.class);
clientResponse.bufferEntity();   
String responseToLog = cr.getEntity(String.class);
log.debug(responseToLog);
MyResponseBean myResponse = cr.getEntity(MyResponseBean.class);

Now the problem is that we cannot call the getEntity() two times since the stream gets consumed the first then we cannot use it second time. Hence the above code gives the exception of No content to map to Object due to end of input . I am sure this is not a very unique requirement and would be common. So what is the best practice or method to do the same?

Siddharth
  • 2,046
  • 5
  • 26
  • 41
  • You can use the Jersey [LoggingFilter](https://jersey.java.net/nonav/apidocs/1.19/jersey/com/sun/jersey/api/client/filter/LoggingFilter.html). Should log the body. If not, you can also provide a PrintStream to capture the input. Or maybe the bufferEntity _should_ work. I don't know. Haven't used Jersey 1 in a while – Paul Samsotha Jun 02 '16 at 11:18
  • I can give this a try but I am not sure how would I wire the LoggingFilter with my existing logger. I will check on this. – Siddharth Jun 03 '16 at 01:39

1 Answers1

7

EDIT

A working example:

String endPoint = "http://localhost:8080/api/places";

Client client = new Client();
ClientResponse cr = client.resource(endPoint).accept("application/json").get(ClientResponse.class);

cr.bufferEntity(); // buffer the entity (HttpInputStream->ByteArrayInputStream)
String res1 = cr.getEntity(String.class); 

cr.getEntityInputStream().reset(); //reset the buffer, this is a ByteArrayInputStream

String res2 = cr.getEntity(String.class);//read again

Ref: check the source of bufferEntity.

csenga
  • 3,819
  • 1
  • 21
  • 31