1. import java.io.IOException;
  2. import java.net.HttpURLConnection;
  3. import java.net.URL;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. public class ApiErrorDetector {
  7. private static final int MAX_RESPONSE_SIZE = 1024 * 1024; // 1MB - limit memory usage
  8. private static final int TIMEOUT_SECONDS = 5;
  9. public static boolean checkApiResponse(String apiUrl) {
  10. try {
  11. URL url = new URL(apiUrl);
  12. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  13. connection.setReadTimeout(TIMEOUT_SECONDS * 1000);
  14. connection.setConnectTimeout(TIMEOUT_SECONDS * 1000);
  15. connection.setUseCaches(false); //Avoid caching for testing
  16. connection.setDoOutput(true); // Required for POST requests. Can be removed if not needed.
  17. connection.setRequestMethod("GET"); // Default is GET, but explicitly set for clarity
  18. int responseCode = connection.getResponseCode();
  19. if (responseCode >= 400) { // Consider 4xx and 5xx as errors
  20. //Check response content to provide more detail
  21. try {
  22. String responseBody = connection.getInputStream().readString(MAX_RESPONSE_SIZE);
  23. if(responseBody != null && !responseBody.isEmpty()){
  24. //Basic error message detection - could be expanded with regex/parsing
  25. if (responseBody.contains("error") || responseBody.contains("exception") || responseBody.contains("failed")) {
  26. System.out.println("API Error: " + responseCode + " - " + responseBody);
  27. return true; // Indicate error
  28. }
  29. }
  30. } catch (IOException e) {
  31. System.err.println("Error reading response body: " + e.getMessage());
  32. }
  33. return true; // Indicate error
  34. }
  35. } catch (IOException e) {
  36. System.err.println("Connection error: " + e.getMessage());
  37. return true; // Indicate error
  38. }
  39. return false; // No error
  40. }
  41. public static void main(String[] args) {
  42. //Example Usage
  43. String apiUrl = "https://example.com/api/data"; // Replace with your API endpoint
  44. boolean hasError = checkApiResponse(apiUrl);
  45. if (hasError) {
  46. System.out.println("API response contains errors.");
  47. } else {
  48. System.out.println("API response is OK.");
  49. }
  50. }
  51. }

Add your comment