javaurlhttp-status-code-500

Java - Check if URL is valid


Need: To check if URL is valid or not (i.e. return status code - 200)

Research: I checked the following threads here - Link1, Link2, Link3

Issue: I tried the solutions provided in those links, but does not work seem to work for these URL's whose http status code is not 200. The program execution kind of hangs at connection.getResponseCode()

Resources: Working link - url1 (i.e. Status Code = 200 & prompt to download file is received in browser) Not working link - url2 (i.e. Status code = 500)

Browser developer tool, showing the return codes for the working URL & not working URL

Browser Developer tool, showing return codes

CODE:

Method 1 -

    try {
                URL u = new URL(url1); // url1 -> Works, url2 -> does not work
                HttpURLConnection connection = (HttpURLConnection) u.openConnection();
                connection.setRequestMethod("GET");
    
                int responseCode = connection.getResponseCode(); // Program hangs here for url2
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    System.out.println("URL is working fine.");
                } else {
                    System.out.println("URL returned a response code: " + responseCode);
                }
            } catch (Exception e) {
                System.out.println("Error occurred while checking the URL: " + e.getMessage());
            }
        }

Method 2 (using Apache Commons UrlValidator class) -

    UrlValidator urlValidator = new UrlValidator();
    System.out.println(urlValidator.isValid(url1)); // Working URL
    System.out.println(urlValidator.isValid(url2)); // Invalid URL, but still shows valid

Added: If anyone can point me as to what I can change to ensure getResponseCode() returns the status code when URL is not working in this case or any other alternative method would help.


Solution

  • For anyone who is facing a similar issue, I managed a workaround using the HTTPstatus API.

    The connection.getResponseCode() hangs for the invalid case, dont know why. Maybe some experts if they have time can check on it.

    Don't know why my question has been down voted, despite following the guidelines & clearly stating what the issue is, the research done & what specific help I seek.