繁体   English   中英

使用 ResponseEntity 从另一个 API 中提取信息

[英]Using ResponseEntity to extract information from another API

我有 2 个 API,可以称它们为 API1 和 API2
API1 是一个系统 API,它从数据库中提取数据并作为结果返回一个字符串列表。
API2 从 API1 中提取信息并按原样返回字符串列表。

现在我的问题是,如果 API1 已关闭,我该如何处理。 我知道我必须使用 ResponseEntity 来提取 HTTP 状态代码,但我无法做到。 以下面的代码为例

API1服务

private static List<String> getData(int attribute1){
//A piece of code that extracts data from the database based on the attribute1 and store the information in a res object<br>
    return res;
}

API2服务

private static List<String> getData(int attribute1){
    String uri="localhost:9191/getData/"+attribute1;
    private RestTemplate restTemplate = new RestTemplate();
    List<String> res = restTemplate.getForObject(uri, List.class);
    return res;
}

我是否需要更改 API1 服务函数的返回类型
如果是这样,他们会是什么样子
不管 API1 中发生了什么,API2 都会发生变化以及如何适应 ResponseEntity
任何帮助将非常感激。

如果您的 API1 出现故障或有任何问题,您将收到使用 RestTemplate 调用“getForObject”方法的异常。 如果您阅读文档,您会看到此方法抛出RestClientException ,这意味着如果您想处理 API1 的任何问题,您需要尝试/捕获该方法并根据您的需要相应地处理异常。 所以,你会有这样的事情:

private static List getData(int attribute1) {

    String uri = "localhost:9191/getData/" + attribute1;

    private RestTemplate restTemplate = new RestTemplate();
    try {
        List res = restTemplate.getForObject(uri, List.class);
        return res;
    } catch(RestClientException rce) {
        // Here you'll handle the exception
    }
}

另请注意,RestClientException 有 3 个直接子类: ResourceAccessExceptionRestClientResponseExceptionUnknownContentTypeException 您可以捕获其中的每一个而不是捕获 RestClientException,因此您可以以不同的方式处理它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM