How to handle MalformedURLException in java?

Java 8Object Oriented ProgrammingProgramming

While working with client-server programming in Java (JSE), if you are using java.net.URL class object in your program, you need to instantiate this class by passing a string representing required URL to which you need to establish connection. If the url you have passed in the string which cannot be parsed or, without legal protocol a MalformedURLException is generated.

Example

In the following Java example we are tring to get establish a connection to a page and publishing the response.

We have tampered the protocol part, changed it to htt, which should be http or, https.

import java.util.Scanner;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetExample {
   public static void main(String[] args) throws IOException {
      String url = "ht://www.tutorialspoint.com/";
      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()+"\n");
         }
         responseReader.close();
         //Printing the Response
         System.out.println(buffer.toString());
      }
   }
}

Runtime Exception

Exception in thread "main" java.net.MalformedURLException: unknown protocol: htt
   at java.net.URL.<init>(Unknown Source)
   at java.net.URL.<init>(Unknown Source)
   at java.net.URL.<init>(Unknown Source)
   at myPackage.HttpGetExample.main(HttpGetExample.java:11)

Handling MalformedURLException

The only solution for this is to make sure that the url you have passed is legal, with a proper protocol.

The best way to do it is validating the URL before you proceed with your program. For validation you can use regular expression or other libraries that provide url validators. In the following program we are using exception handling itself to validate the 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 HttpGetExample {
   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 {
      String url = "ht://www.tutorialspoint.com/";
      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()+"\n");
            }
            responseReader.close();
            //Printing the Response
            System.out.println(buffer.toString());
         }
      }else {
         System.out.println("Enter valid URL");
      }
   }
}

Output

Enter valid URL
raja
Published on 06-Aug-2019 12:35:56
Advertisements