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


The URL class of the java.net 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.

Example

import java.util.Scanner;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
public class ValidatingURL {
   public static boolean isUrlValid(String url) {
      try {
         URL obj = new URL(url);
         obj.toURI();
         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.in);
      System.out.println("Enter an URL");
      String url = sc.next();
      if(isUrlValid(url)) {
         URL obj = new URL(url);
         //Opening a connection
         HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
         //Sending the request
         conn.setRequestMethod("GET");
         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()) {
               buffer.append(responseReader.nextLine()+"
");             }             responseReader.close();             //Printing the Response             System.out.println(buffer.toString());          }       }else {          System.out.println("Enter valid URL");       }    } }

Output

Enter an URL
ht://www.tutorialspoint.com/
Enter valid URL

Updated on: 09-Sep-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements