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

我需要调用两个 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 编写的。


慕妹3242003
浏览 84回答 1
1回答

胡说叔叔

您可以用来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();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java