Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class ApiSwitch {
- private static final String[] apiKeys = {"API_KEY_1", "API_KEY_2", "API_KEY_3"};
- private static int currentKey = 0;
- public static void main(String[] args) {
- try {
- String apiUrl = "https://api.example.com/data";
- String responseData = fetchData(apiUrl);
- System.out.println("Response: " + responseData);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- private static String fetchData(String apiUrl) throws IOException {
- String apiKey = apiKeys[currentKey];
- URL url = new URL(apiUrl);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setRequestProperty("Authorization", "Bearer " + apiKey);
- connection.setRequestMethod("GET");
- int responseCode = connection.getResponseCode();
- if (responseCode == HttpURLConnection.HTTP_OK) {
- BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- StringBuilder response = new StringBuilder();
- String line;
- while ((line = reader.readLine()) != null) {
- response.append(line);
- }
- reader.close();
- return response.toString();
- } else {
- System.out.println("Request failed with API key: " + apiKey);
- currentKey = (currentKey + 1) % apiKeys.length;
- return fetchData(apiUrl);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement