MalformedURLException

java.net.MalformedURLException – How to solve MalformedURLException

In this example we are going to talk about java.net.MalformedURLException. It is a subclass of IOException so it is a checked exception. What you should know is that MalformedURLException is an exception that occurs when you are trying to connect to a URL from your program but your client cannot parse the URL correctly.
 

1. A simple HTTP client

To demonstrate that exception, we are going to to create a simple HTTP client. This client will have on method that takes as input a URL string and returns the response, e.g the HTML code of the page that we are hitting.

MalformedURLExceptionExample.java:

package com.javacodegeeks.core.lang.NumberFormatExceptionExample;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MalformedURLExceptionExample {

	private static final String USER_AGENT = "Mozilla/5.0";
	private static final String URL = "http://examples.javacodegeeks.com/core-java/io/bufferedreader/how-to-get-the-standard-input-in-java/";

	public static void main(String[] args) {
		try {
			System.out.println(sendGetRequest(URL));

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String sendGetRequest(String urlString) throws IOException {

		URL obj = new URL(urlString);
		HttpURLConnection httpConnection = (HttpURLConnection) obj
				.openConnection();

		httpConnection.setRequestMethod("GET");

		httpConnection.setRequestProperty("User-Agent", USER_AGENT);

		int responseCode = httpConnection.getResponseCode();
		if (responseCode == 200) {

			BufferedReader responseReader = new BufferedReader(new InputStreamReader(
					httpConnection.getInputStream()));
			
			String responseLine;
			StringBuffer response = new StringBuffer();

			while ((responseLine = responseReader.readLine()) != null) {
				response.append(responseLine+"\n");
			}
			responseReader.close();

			// print result
			return response.toString();
		}
		return null;

	}
}

This will output:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><
html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" 
xmlns:fb="http://www.facebook.com/2008/fbml" ><head profile="http://gmpg.org/xfn/11"><link rel="stylesheet" type="text/css" 
href="http://a5e2fba00d8bcb729d89839f.javacodegeeks.netdna-cdn.com/wp-content/w3tc/min/0488f/default.include.8204a8.css" media="all" />
<script type="text/javascript" src="http://a5e2fba00d8bcb729d89839f.javacodegeeks.netdna-cdn.com/wp-content/w3tc/min/0488f/default.include.c46d29.js"></script><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>How to get the standard input in Java | Examples Java Code Geeks</title><link
...
...
...

As you can see, you get the normal HTTP response you’d expect.

Now. let’s see what happens if you change:

private static final String URL = "http://examples.javacodegeeks.com/core-java/io/bufferedreader/how-to-get-the-standard-input-in-java/";

to

private static final String URL = "htp://examples.javacodegeeks.com/core-java/io/bufferedreader/how-to-get-the-standard-input-in-java/";

I’ve changed http to htp. Let’s see what happens now:

java.net.MalformedURLException: unknown protocol: htp
	at java.net.URL.<init>(URL.java:592)
	at java.net.URL.<init>(URL.java:482)
	at java.net.URL.<init>(URL.java:431)
	at com.javacodegeeks.core.lang.NumberFormatExceptionExample.MalformedURLExceptionExample.sendGetRequest(MalformedURLExceptionExample.java:28)
	at com.javacodegeeks.core.lang.NumberFormatExceptionExample.MalformedURLExceptionExample.main(MalformedURLExceptionExample.java:17)

So as you can see the message that accompanies that exception is pretty informative of the cause of the problem.

In general, any URL that doesn’t follow the URL Specification cannot be parsed by this client and it will complain with a MalformedURLException.

2. How to solve MalformedURLException

In general, the message that follows the exception is usually very informative of what has gone wrong. In the previous example we’ve read unknown protocol: htp, so that means that something was wrong with the protocol we’ve chosen. Usually, it is best to log the string that you give as input to any method that might throw a MalformedURLException. That way you can be sure that the method get’s the intended input correctly. Don’t forget to read the URL Specification and make sure the URL you are providing is valid. Of course input validation, like we’ve shown in java.lang.NumberFormatException – How to solve NumberFormatException with regular expressions or any kind of input validation, is a must for very sensitive applications.

Download Source Code

This was an example on java.net.MalformedURLException and how to solve MalformedURLException. You can download the source code of this example here : MalformedURLExceptionExample.zip

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Warvin Mogate
6 years ago

Hi Sir this is Warvin from Philippines, I would like to ask how to solve java.net.MalformedURLException with Jasper Report in desktop application developed in JAVA Netbeans. It is developed connected to the server which ask the user to enter the URL of the server(database). when I tried to connect the application to the localhost and activate the jasperviewer, it unable to display the data instead java.netMalformedURLException. What must i do to fix this?

Back to top button