anand elson
anand elson

Reputation: 21

Log the request body of JSON @ Jersey Rest WS

How do I print/Log the request body of JSON from below code @ Rest WS with Jersey in Java. I can log the response for this. I am struggling to log/print the exact request body.

Thanks in advance.

WebTarget target = client.target(url);

    //authentication strings
    String authString = "username:password";
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);

    Response res = target.request(MediaType.APPLICATION_JSON)   
            .header("content-type", "application/json")
            .header("Authorization", "Basic " + authStringEnc)
            .header("accept", "application/json,text/plain")    
            .header("X-senderTimestamp", new Timestamp(System.currentTimeMillis()))
            .header("X-appCode", "IVR")
            .header("X-sessionId", XsessionId)
            .post(Entity.entity(getAccountInfoInputBean, MediaType.APPLICATION_JSON));

Upvotes: 2

Views: 4892

Answers (2)

cassiomolin
cassiomolin

Reputation: 131137

Jersey 2.23 and later

In Jersey 2.23 and later, the LoggingFeature will do the trick for you. It must be registered as following:

ClientConfig clientConfig = new ClientConfig();
clientConfig.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY_CLIENT, 
                      LoggingFeature.Verbosity.PAYLOAD_ANY);
Client client = ClientBuilder.newBuilder(clientConfig);

With the default verbosity settings (LoggingFeature.Verbosity.PAYLOAD_TEXT), the request and response headers will be logged, as well as the entity if considered a readable text. The entity is considered a readable text, if the media type is text/* or is one of:

  • application/atom+xml
  • application/json
  • application/svg+xml
  • application/x-www-form-urlencoded
  • application/xhtml+xml
  • application/xml

Note that the entity is logged up to the specified maximum number of bytes (see LoggingFeature.LOGGING_FEATURE_MAX_ENTITY_SIZE).

Have a look at the Jersey documentation about logging for more details.

Older versions

In older versions, use LoggingFilter. According to the documentation, as of Jersey 2.23 and later, this filter has been deprecated and will be removed soon.

Upvotes: 3

Issam El-atif
Issam El-atif

Reputation: 2496

You can use LoggingFilter to log to System.out.

client.addFilter(new LoggingFilter(System.out));
WebTarget target = client.target(url);

Upvotes: 0

Related Questions