为了账号安全,请及时绑定邮箱和手机立即绑定

如何按顺序进行多个 API 调用

如何按顺序进行多个 API 调用

慕妹3242003 2023-09-27 21:22:48
我需要调用两个 API A1 和 A2,但不是并行调用。仅当 A1 在其 JSON 响应中返回某个标志值时,A2 才会被调用。我知道如何使用 Httpclient 在 java 中进行 http 调用。一种方法是编写一个代码来进行第一次调用并解析其响应,然后再次使用相同的代码进行另一个调用。是否有任何其他智能方法可以为我们自动化此过程,我将传递请求和条件第二个需要像 Rxjava 中那样调用下面是 Rxjava 代码片段(参考:(RxJava 组合请求序列))api1.items(queryParam) .flatMap(itemList -> Observable.fromIterable(itemList))) .flatMap(item -> api2.extendedInfo(item.id())) .subscribe(...)我怎样才能在Java中完成这个任务呢?是否有任何已经存在的 Java 功能允许我进行多个顺序调用?我尝试寻找现有的解决方案,但它们不是用 Java 编写的。
查看完整描述

1 回答

?
胡说叔叔

TA贡献1804条经验 获得超8个赞

您可以用来HttpURLConnection进行 API 调用。


检查响应并相应地触发另一个呼叫。


像这样的东西


public static void main(String[] args) throws IOException {


    String response1 = sendGET("http://url1");

    if(response1 != null && response1.contains("true")){

        String response2 = sendGET("http://url2");

    }


}


private static String sendGET(String url) throws IOException {

    URL obj = new URL(url);

    StringBuffer response = new StringBuffer();

    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("GET");

    int responseCode = con.getResponseCode();

    System.out.println("GET Response Code :: " + responseCode);

    if (responseCode == HttpURLConnection.HTTP_OK) { // success

        BufferedReader in = new BufferedReader(new InputStreamReader(

                con.getInputStream()));

        String inputLine;

        while ((inputLine = in.readLine()) != null) {

            response.append(inputLine);

        }

        in.close();


        // print result

        System.out.println(response.toString());

    } else {

        System.out.println("GET request not worked");

    }

    return response.toString();

}


查看完整回答
反对 回复 2023-09-27
  • 1 回答
  • 0 关注
  • 83 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信