Advertisement
Sonnet_Songbird

API key switcher

Nov 28th, 2023
889
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.67 KB | Source Code | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.net.HttpURLConnection;
  5. import java.net.URL;
  6.  
  7. public class ApiSwitch {
  8.     private static final String[] apiKeys = {"API_KEY_1", "API_KEY_2", "API_KEY_3"};
  9.     private static int currentKey = 0;
  10.  
  11.     public static void main(String[] args) {
  12.         try {
  13.             String apiUrl = "https://api.example.com/data";
  14.             String responseData = fetchData(apiUrl);
  15.             System.out.println("Response: " + responseData);
  16.         } catch (IOException e) {
  17.             e.printStackTrace();
  18.         }
  19.     }
  20.  
  21.     private static String fetchData(String apiUrl) throws IOException {
  22.         String apiKey = apiKeys[currentKey];
  23.         URL url = new URL(apiUrl);
  24.         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  25.         connection.setRequestProperty("Authorization", "Bearer " + apiKey);
  26.         connection.setRequestMethod("GET");
  27.  
  28.         int responseCode = connection.getResponseCode();
  29.  
  30.         if (responseCode == HttpURLConnection.HTTP_OK) {
  31.             BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  32.             StringBuilder response = new StringBuilder();
  33.             String line;
  34.  
  35.             while ((line = reader.readLine()) != null) {
  36.                 response.append(line);
  37.             }
  38.  
  39.             reader.close();
  40.             return response.toString();
  41.         } else {
  42.             System.out.println("Request failed with API key: " + apiKey);
  43.             currentKey = (currentKey + 1) % apiKeys.length;
  44.             return fetchData(apiUrl);
  45.         }
  46.     }
  47. }
  48.  
Tags: Java Exemple
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement