A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/check-if-url-is-valid-or-not-in-java/ below:

Check if URL is valid or not in Java

Check if URL is valid or not in Java

Last Updated : 30 May, 2018

Given a URL as string, we need to find if the given URL is valid or not.

Input : str = "https://www.geeksforgeeks.org/"
Output : Yes


Input : str = "https:// www.geeksforgeeks.org/"
Output : No
Note that there is a space after https://
Using java.net.url

We can use

java.net.url

class to validate a URL. The idea is to create a URL object from the specified String representation. If we do not get exception while creating the object, we return true. Else we return false.

Java
// Java program to check if a URL is valid 
// using java.net.url
import java.net.URL;

class Test {

    /* Returns true if url is valid */
    public static boolean isValid(String url)
    {
        /* Try creating a valid URL */
        try {
            new URL(url).toURI();
            return true;
        }
        
        // If there was an Exception
        // while creating URL object
        catch (Exception e) {
            return false;
        }
    }
    
    /*driver function*/    
    public static void main(String[] args)
    {
        String url1 = "https://www.geeksforgeeks.org/";
        if (isValid(url1)) 
            System.out.println("Yes");
        else
            System.out.println("No");     
            
        String url2 = "http:// www.geeksforgeeks.org/";
        if (isValid(url2)) 
            System.out.println("Yes");
        else
            System.out.println("No");                
    }
}

Output:

Yes
No


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4