亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何按順序進行多個 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 關注
  • 104 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號