How to check if an URL is valid or not using Java?

Java 8Object Oriented ProgrammingProgramming

The URL class of the package represents a Uniform Resource Locator which is used to point a resource(file or, directory or a reference) in the worldwide web.

This class provides various constructors one of them accepts a String parameter and constructs an object of the URL class. While passing URL to this method if you used an unknown protocol or haven’t specified any protocol this method throws a MalformedURLException.

Similarly, the toURI() method of this class returns an URI object of the current URL. If the current URL is not properly formatted or, syntactically incorrect according to RFC 2396 this method throws a URISyntaxException.

In a separate method invoke create an URL object by passing the requires URL in Sting format and invoke the toURI() method. Wrap this code in try-catch blocks, if an exception is thrown (MalformedURLException or, URISyntaxException) that indicates there is an issue with the given URL.


import java.util.Scanner;
public class ValidatingURL {
   public static boolean isUrlValid(String url) {
      try {
         URL obj = new URL(url);
         return true;
      } catch (MalformedURLException e) {
         return false;
      } catch (URISyntaxException e) {
         return false;
   public static void main(String[] args) throws IOException {
      Scanner sc = new Scanner(;
      System.out.println("Enter an URL");
      String url =;
      if(isUrlValid(url)) {
         URL obj = new URL(url);
         //Opening a connection
         HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
         //Sending the request
         int response = conn.getResponseCode();
         if (response == 200) {
            //Reading the response to a StringBuffer
            Scanner responseReader = new Scanner(conn.getInputStream());
            StringBuffer buffer = new StringBuffer();
            while (responseReader.hasNextLine()) {
            //Printing the Response
      }else {
         System.out.println("Enter valid URL");


Enter an URL
Enter valid URL
Updated on 09-Sep-2019 07:30:14