import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class ApiErrorDetector {
private static final int MAX_RESPONSE_SIZE = 1024 * 1024; // 1MB - limit memory usage
private static final int TIMEOUT_SECONDS = 5;
public static boolean checkApiResponse(String apiUrl) {
try {
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(TIMEOUT_SECONDS * 1000);
connection.setConnectTimeout(TIMEOUT_SECONDS * 1000);
connection.setUseCaches(false); //Avoid caching for testing
connection.setDoOutput(true); // Required for POST requests. Can be removed if not needed.
connection.setRequestMethod("GET"); // Default is GET, but explicitly set for clarity
int responseCode = connection.getResponseCode();
if (responseCode >= 400) { // Consider 4xx and 5xx as errors
//Check response content to provide more detail
try {
String responseBody = connection.getInputStream().readString(MAX_RESPONSE_SIZE);
if(responseBody != null && !responseBody.isEmpty()){
//Basic error message detection - could be expanded with regex/parsing
if (responseBody.contains("error") || responseBody.contains("exception") || responseBody.contains("failed")) {
System.out.println("API Error: " + responseCode + " - " + responseBody);
return true; // Indicate error
}
}
} catch (IOException e) {
System.err.println("Error reading response body: " + e.getMessage());
}
return true; // Indicate error
}
} catch (IOException e) {
System.err.println("Connection error: " + e.getMessage());
return true; // Indicate error
}
return false; // No error
}
public static void main(String[] args) {
//Example Usage
String apiUrl = "https://example.com/api/data"; // Replace with your API endpoint
boolean hasError = checkApiResponse(apiUrl);
if (hasError) {
System.out.println("API response contains errors.");
} else {
System.out.println("API response is OK.");
}
}
}
Add your comment