Home > Software design >  Send multiple API requests simultaneously with different authorization header for each API Call requ
Send multiple API requests simultaneously with different authorization header for each API Call requ

Time:07-15

I am struggling in sending multiple API requests simultaneously, below are the steps of which I am doing in order to send multiple API calls simultaneously:

  1. Creating hashmap with 40 authorization values.
  2. iterating over the hashmap in order to retrieve different authorization value for each call.

I know how to make it sequentially, I want to be able to do it with threads.

This is my code:

private void createUsers() throws ApiException {
    AuthAPI authAPI = new AuthAPI(HOST);
    usersMap = new HashMap<>();
    for (int i = 0; i < 40 - 1; i  ) {
        String USER_NAME = "Introductory Content User "   StringUtils.getRandomString(5, true, false);
        usersAPIUnitTest.createUser(USER_NAME, UserRole.ADMIN, "", "", "");
        String email = UsersAPIUnitTest.getEmail();
        System.out.println(email);
        String userToken = authAPI.generateToken(email);
        usersMap.put(USER_NAME, userToken);
    }
}

Then I use this method to send the api calls:

public void sendMultipleAPIRequests() throws IOException {
        for(Map.Entry mapElement : usersMap.entrySet()){
            LabAPIChecker labAPIChecker = new LabAPIChecker(HOST, mapElement.getValue());
            JsonObject jsonObject = labAPIChecker.launchLabGetRequest();//this line perform simple 'get' request
        }
        
    }

CodePudding user response:

You can do all this with standard java tools. You will need to use ScheduledExecutorService or possibly just an ExecutorService To get an istance of one use [Executors] class2. You will need to create (or modify) your own class to implement Runnable interface where method run() would be responsible for sending a single request. Than you will need to submit all your Runnables to your ScheduledExecutorService to run at the same time. Set the number of threads equal to the number of your runnables and they will run concurrently

CodePudding user response:

The resulting code following @michael-gantman suggestion:

public void sendMultipleAPIRequests() throws IOException 
{
    ExecutorService executorService = Executors.newFixedThreadPool(10); // max 10 concurrent threads
    for (Map.Entry mapElement : usersMap.entrySet()) {
        Runnable thread = () -> {
          LabAPIChecker labAPIChecker = new LabAPIChecker(HOST, mapElement.getValue());
          JsonObject jsonObject = labAPIChecker.launchLabGetRequest();
        };
        executorService.execute(thread);
     }
     executorService.shutdown(); 
 }

All credit goes to @michael-gantman

  • Related