How to Fix Malformed Url Exception

Posted by Marta on September 23, 2021 Viewed 8333 times

Card image cap

In this article, you will learn the main reason why you will face the Malformed Url Exception in Java along with a few different examples and how to fix it.

I think it is essential to understand why this error occurs, since the better you understand the error, the better your ability to avoid it.

This tutorial contains some code examples and possible ways to fix the error. Malformed Url Exception

To understand this issue firstly we need to understand what is a URL.

URL stands for Unique Resource Locator, meaning identifier that uniquely represents a resource in the web. This resource could be an HTML page, CSS file, an image, etc. malformed url exception

Let’s see what’s the anatomy of a URL:

  • Protocol: Indicates the communication protocol the browser should use to send request, usually HTTP or HTTPS.
  • Domain Name: The domain name can also be an IP and it represents the web server that hold the resource.
  • Port: The port is the the unique number that indicate the process that should access to reach the resource. Typically the port is 80 for HTTP and 443 for HTTPS, however this is configurable.
  • Path to Resource: Path to reach the resource in the web server.

Why is this information important? In general, You will see this error if the URL used in your code is not following the above syntax.

This is an obvious case, however there are cases that aren’t so straightforward. Let’s see a few examples

Example #1: Parsing an XML in Java

Let’s see a code snippet that will read an XML string, and access some information from it. The XML contains employees information: id and name, and you would like to access the employees names. Therefore, the code will parse the XML and then access the employees names.

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
                "     <employees>" +
                "        <employee>" +
                "           <id>1</id>" +
                "           <name>Jeremy</name>"+
                "        </employee>"+
                "        <employee>"+
                "           <id>2</id>"+
                "           <name>Julia</name>"+
                "        </employee>"+
                "     </employees>";
        //Parse XML
        Document dom = db.parse(xml);
      // Print the employees names

However when you run this code you get the following exception:

Exception in thread "main" no protocol: <?xml version="1.0" encoding="utf-8"?> etc...

This error message can be very misleading and confusing because actually there is no URL so, how can it be malformed? The issue is at line 26, when the code is trying to parse the XML.

The .parse() method can be used in five ways (See documentation here):

In our case since we are passing a String as the argument, the code is expecting the String to be a URI. And it is going to use this URI to fetch the XML content. However we passed the XML content directly, so Java doesn’t know what to do and return an exception because the URI doesn’t follow the URL anatomy.

How to Fix it

To fix this problem, you have to pass your XML String wrapped as a File, and InputSource or InputStream. Doing so, Java understands that you are providing the XML content directly, instead of a URL from where the content can be fetched. Consequently replacing line 26 “Document dom = db.parse(xml); with one of following line, will fix the exception:

 Document dom = db.parse(new InputSource(new StringReader(xml)));
// Please note the file should contain the XML
Document dom = db.parse(new File("file_containing.xml"));

Example #2: Quotes in the URL!

You will also face the malformed url exception when you are trying to convert your String to a URL, however your String is surrounded by extra double or single quotes, as follows:

public static void main(String[] args) throws IOException{
	URL url = new URL("''");

This might seem obvious but it could be easily missed if you are reading this url from somewhere else, for instance, an XML file. Let’s consider the following code snippet, which reads an XML String and parse it

String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
                "     <websites>" +
                "        <site>" +
                "           <url>''</url>" +
                "        </site>"+
                "     </websites>";

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(new InputSource(new StringReader(xml)));
// Extract the URL from XML as a String
String urlFromXML = dom.getElementsByTagName("url").item(0).getTextContent();
// Convert the String to URL
URL url = new URL(urlFromXML);

This code returns the malformed url exception:

Exception in thread "main" no protocol: ''

The best way to fix this issue is making sure there is no single or double quotes surrounding the url in the XML. Or you can also delete the single quotes as follows: 

// Extract the URL from XML as a String
String urlFromXML = dom.getElementsByTagName("url").item(0).getTextContent();

// Remove single quotes 
urlFromXML = urlFromXML.replace("'","");

// Convert the String to URL
URL url = new URL(urlFromXML);


In summary, we have seen a few scenarios where you could face the “ malformed url exception” error. Additionally we covered how you can fix this error by making sure the URL doesn’t contain quotes, and that in case of parsing XML we used the correct types based on what we are passing as argument to the parse method.

I hope you enjoy this article, and understand this issue better to avoid it when you are programming.

Thank you so much for reading and supporting this blog!

Happy Coding!

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java