Get native REST service error in Unirest

sag picture sag · Nov 28, 2015 · Viewed 7.7k times · Source

We are using Unirest as REST client. Below is the sample code using which we are invoking REST service

HttpResponse<JsonNode> response = Unirest
  .post(url)
  .header(HEADER_CONTENT_TYPE, HEADER_VALUE_APPLICATON_JSON)
  .body(payload)
  .asJson();

This is absolutely when REST service returns json. In case of error, REST service that I am using is not returning json response. Instead it returns html error page.

Since Unirest is trying to convert the html into json, getting the following issue

Caused by: com.mashape.unirest.http.exceptions.UnirestException: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
    at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:143)
    at com.mashape.unirest.request.BaseRequest.asJson(BaseRequest.java:68)

In this case we are just getting this InvalidJsonException and the actual html error page is lost. We need to display the html error page in our application in case of error.

How can we get the original REST service error, in situation like this?

Answer

Dimitar II picture Dimitar II · Feb 7, 2016

Since you cannot rely on the returned content type, the workaround is to treat the response as String:

  HttpResponse<String> response = Unirest
      .post(url)
      .header(HEADER_CONTENT_TYPE, HEADER_VALUE_APPLICATON_JSON)
      .body(payload)
      .asString();

This way you will have access to the return status code. Unirest will not try to parse the result to JSON, so you need to do it yourself (if the status code indicates success).