在 Unirest 中获取本机 REST 服务错误

Get native REST service error in Unirest

我们使用 Unirest 作为 REST 客户端。下面是我们用来调用 REST 服务的示例代码

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

这绝对是REST服务时returnsjson。如果出现错误,我使用的 REST 服务不会返回 json 响应。取而代之的是 returns html 错误页面。

由于 Unirest 正在尝试将 html 转换为 json,出现以下问题

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)

在这种情况下,我们只是得到这个 InvalidJsonException,实际的 html 错误页面丢失了。如果出现错误,我们需要在我们的应用程序中显示 html 错误页面。

在这种情况下,我们如何获取原始 REST 服务错误?

由于您不能依赖 returned 内容类型,解决方法 是将响应视为字符串:

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

这样您就可以访问 return 状态代码。 Unirest 不会尝试将结果解析为 JSON,因此您需要自己执行(如果状态码指示成功)。