Search code examples
javaurl-validation

How to validate a URLs status


I have excelsheet named as Validationstatuscode.xlsx which consists of list of URLs on Column A of sheet 1. I want to validate all URLs which show http status 200 or 400. Till now i've used http://httpstatus.io/ to validate 100 URLs at 1 shot but now the count has increased. So is there possible in java to validate the URLs? Though i've knowledge in java but dont know how to do this?


Solution

  • You can use java.net.HttpURLConnection for this as in the sample below. The key here is the getResponseCode method that will return the HTTP code, i.e. 200, 400... .

    package so;
    
    import java.io.IOException;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class HttpRequest {
    
        private int getWebPageStatus(String url) {
    
            HttpURLConnection con = null;
            try {
                con = (HttpURLConnection) new URL(url).openConnection();
                return con.getResponseCode();
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (con != null) {
                    con.disconnect();
                }
            }
    
            return -1;
        }
    
        public static void main(String[] args) {
            HttpRequest request = new HttpRequest();
    
            System.out.println("https://login.yahoo.com  :" + request.getWebPageStatus("https://login.yahoo.com"));
            System.out.println("https://www.google.co.in :" + request.getWebPageStatus("https://www.google.co.in"));
            System.out.println("https://www.gmail.com    :" + request.getWebPageStatus("https://www.gmail.com"));
            System.out.println("https://xyz.co.in        :" + request.getWebPageStatus("https://xyz.co.in"));
        }
    
    }