【问题标题】:500 STATUS WHEN CONVERTING RESPONSE TO STRING JAVA将响应转换为字符串 JAVA 时出现 500 状态
【发布时间】:2020-09-23 11:10:33
【问题描述】:

我正在使用 bing api 来获取两点之间的距离。 我在我的项目中添加了正确的数据验证。我想捕捉这个异常:

所以我想对用户说,嘿,您的目的地地址不正确,请输入正确的地址。

我在我的应用程序中使用 spring boot。我使用休息模板。我想将此响应粘贴到 String,然后对其进行处理。这是我的代码:

{  final String uri = "http://dev.virtualearth.net/REST/V1/Routes/Driving" + "?waypoint.0=ulica" + string1 + "&waypoint.1=ulica" + string2 +
            "&key=" + apiKey;
    String result = "";
    RestTemplate restTemplate = new RestTemplate();
        result = restTemplate.getForObject(uri, String.class);
    }

如您所见,我想在 String.class 中得到响应。

这是我得到的错误(java 将此响应转换为字符串时出现问题,这就是为什么我得到 500 响应,而不是 404 响应):

我希望得到 Bing 的原始回复(我的帖子中的第一个 ss),而不是 500 个。 怎么做?

【问题讨论】:

  • 不确定,但对我而言,您似乎要么不使用@ResponseBody@RestController
  • 我在端点上面有restcontroller,为什么是responseBody?

标签: java spring-boot resttemplate bing


【解决方案1】:

您可以将 Bing API 调用放在 try-catch 块中(恕我直言,这是一个很好的做法),捕获 RestClientExceptionRestClientResponseException 并处理它,例如,通过抛出映射到的您自己的应用程序的异常404 响应。例如:

final String uri = "http://dev.virtualearth.net/REST/V1/Routes/Driving" + "?waypoint.0=ulica" + string1 + "&waypoint.1=ulica" + string2 +
       "&key=" + apiKey;
try {
    String result = "";
    RestTemplate restTemplate = new RestTemplate();
    result = restTemplate.getForObject(uri, String.class);
} catch (RestClientResponseException e) {
    if (e.getRawStatusCode() == 404) {
       // Application-specific exception with reasonable meaning and mapping for clients
       throw new UnknownDestinationException(e.getResponseBodyAsString());
    }
    throw e;   // Otherwise just throw it
}

【讨论】:

  • 我没有尝试你的解决方案,但它看起来不错,都是为了捕捉异常,所以你的解决方案也应该是正确的
【解决方案2】:

这里是解决方案:

  // Create needed variables
    final String uri = "http://dev.virtualearth.net/REST/V1/Routes/Driving" + "?waypoint.0=ulica" + string1 + "&waypoint.1=" + string2 +
            "&key=" + bing_api_key;
    String result = "";
    RestTemplate restTemplate = new RestTemplate();
    // Get bing api response
    try {
        result = restTemplate.getForObject(uri, String.class);
    }
    catch (final HttpClientErrorException e) {
        result = e.getResponseBodyAsString();
    }

这一行: final HttpClientErrorException e 导致我得到 404 错误,而不是 500。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 2012-10-14
    相关资源
    最近更新 更多