Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. 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.

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

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close