程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用 ResponseEntity 从另一个 API 中提取信息大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决使用 ResponseEntity 从另一个 API 中提取信息?

开发过程中遇到使用 ResponseEntity 从另一个 API 中提取信息的问题如何解决?下面主要结合日常开发的经验,给出你关于使用 ResponseEntity 从另一个 API 中提取信息的解决方法建议,希望对你解决使用 ResponseEntity 从另一个 API 中提取信息有所启发或帮助;

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

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

API1 服务

websites_enable_app_service_storage

API2 服务

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;
}

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

解决方法

如果您的 API1 出现故障或有任何问题,您将收到使用 RestTemplate 调用“getForObject”方法的异常。如果您阅读 documentation,您会看到此方法抛出 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,这样您就可以用不同的方式处理它们。

大佬总结

以上是大佬教程为你收集整理的使用 ResponseEntity 从另一个 API 中提取信息全部内容,希望文章能够帮你解决使用 ResponseEntity 从另一个 API 中提取信息所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。