Shawn Strickland Shawn Strickland - 4 months ago 100
Java Question

Not receiving body on Apache Wink Rest Client error with JAX-RS Application

I need to make a JSON API call to an external source inside of my JAX-RS application. From my research, in order to do this I need to use

RestClient()
, which works. But only when I get a successful response back. It can not parse the body when the status code is anything other than
400
. Here's an example of working code when I get a
200 status
:

Resource resource = client.resource("https://api.paytrace.com/v1/customer/create");
String response = resource
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + accessToken)
.accept(MediaType.APPLICATION_JSON)
.post(String.class, paytraceJSON);


I'm currently just trying to log out
response
but get nothing when the response details back an error in the body. Is there a better way to deal with this, so I can echo back errors from the service API I'm using within my own?

Answer

Instead of using Resource to handle everything, I was able to leverage casting to ClientResponse instead of String which will return me back errors instead of just text when the response fails (for whatever reason).

I need to make a JSON API call to an external source inside of my JAX-RS application. From my research, in order to do this I need to use RestClient(), which works. But only when I get a successful response back. It can not parse the body when the status code is anything other than 400. Here's an example of working code when I get a 200 status:

Old way:

Resource resource = client.resource("https://api.com");
String response = resource
    .contentType(MediaType.APPLICATION_JSON)
    .header("Authorization", "Bearer " + accessToken)
    .accept(MediaType.APPLICATION_JSON)
    .post(String.class, payload);
//Parse the String here to turn it into a JSONObject

New way:

Resource resource = client.resource("https://api.com/");
ClientResponse response = resource.contentType("application/json")
        .accept("application/json")
        .header("Authorization", "Bearer " + accessToken)
        .post(payload);
JSONObject customerResponseObject = response.getEntity(JSONObject.class);