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

How to make multiple API calls in sequential order

我需要同时调用两个 API A1 和 A2。仅当 A1 returns 其 JSON 响应中的某个标志值时,A2 才会被调用。

我知道如何使用 Httpclient 在 java 中进行 http 调用。一种方法是编写一个代码来进行第一次调用并解析其响应,然后再次使用相同的代码进行另一个 call.Is 他们任何其他智能方式为我们自动化这个过程,我将传递请求和条件在哪一秒需要像在 Rxjava

中那样调用

以下是 Rxjava 代码片段(参考:())

api1.items(queryParam)
.flatMap(itemList -> Observable.fromIterable(itemList)))
.flatMap(item -> api2.extendedInfo(item.id()))
.subscribe(...)

如何在 Java 中完成此操作?是否有任何 Java 功能已经存在并允许我进行多个顺序调用?

我尝试搜索现有的解决方案,但 Java 中没有。

您可以使用 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();
}