1. import java.io.IOException;
  2. import java.net.URL;
  3. import java.net.URLConnection;
  4. public class HttpErrorChecker {
  5. public static void main(String[] args) {
  6. String urlString = "https://www.example.com/nonexistent_page"; // Replace with your URL
  7. try {
  8. URL url = new URL(urlString);
  9. URLConnection connection = url.openConnection();
  10. connection.connect(); // Initiate the connection
  11. //Get the response status code
  12. int statusCode = connection.getResponseCode();
  13. if (statusCode >= 400) {
  14. System.err.println("HTTP Error: " + statusCode); // Print error code
  15. System.err.println("Response: " + connection.getResponseMessage()); //Display message
  16. } else {
  17. System.out.println("Request successful. Status Code: " + statusCode);
  18. }
  19. } catch (IOException e) {
  20. System.err.println("IOException: " + e.getMessage()); //Handle connection errors
  21. }
  22. }
  23. }

Add your comment