priyadhingra19
priyadhingra19

Reputation: 337

How to make multiple API calls in sequential order

I need to call two APIs A1 and A2 but not parallelly. A2 would get called only if A1 returns some flag value in its JSON response.

I'm aware of how to make an http call in java using Httpclient. one way is to write one code to make first call and parse its response and again use the same code to make another call.Is their any other smart way which automate this process for us where I will pass both the request and the condition on which second one need to call like it is possible in Rxjava

Follwing is the Rxjava code snippet (Reference : (RxJava Combine Sequence Of Requests))

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

How can I accomplish this in Java? Is there any Java feature that already exists and will allow me to make a multiple sequential call?

I tried searching for existing solutions but they were not in Java.

Upvotes: 0

Views: 6687

Answers (1)

MyTwoCents
MyTwoCents

Reputation: 7624

You can use HttpURLConnection to do an API call.

Check response and accordingly trigger another call.

Something like this

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

Upvotes: 0

Related Questions