· last year · Nov 28, 2023, 07:30 AM
1import java.io.BufferedReader;
2import java.io.IOException;
3import java.io.InputStreamReader;
4import java.net.HttpURLConnection;
5import java.net.URL;
6
7public 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