Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MalformedURLException although I have already replaced spaces with %20

Tags:

java

url

String url = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins="+origin+"&destinations="+destination+"&mode=driving&sensor=false&language=en-EN&units=imperial";
url = url.replaceAll(" ", "%20");

Output :

http://maps.googleapis.com/maps/api/distancematrix/xml?origins=150%20Sutter%20St%20San%20Francisco,%20CA,%20United%20States&destinations=1%20Palmer%20Sq%20E
Princeton,%20NJ%2008542&mode=driving&sensor=false&language=en-EN&units=imperial

But I am getting an error saying :

java.net.MalformedURLException: Illegal character in URL

Can some one help me out ..

like image 850
user3742241 Avatar asked Jun 15 '14 12:06

user3742241


People also ask

How do I fix MalformedURLException?

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.

What is MalformedURLException in Java?

public class MalformedURLException extends IOException. Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.


1 Answers

(Note: see update below)

Use the URLEncoder class from the java.net package. Spaces are not the only characters that need to be escaped in URLs, and the URLEncoder will make sure that all characters that need to be encoded are properly encoded.

Here's a small example:

String url = "http://...";
String encodedUrl = null;

try {
    encodedUrl = URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException ignored) {
    // Can be safely ignored because UTF-8 is always supported
}

Update

As pointed out in the comments and other answers to this question, the URLEncoder class is only safe to encode the query string parameters of a URL. I currently rely on Guava's UrlEscapers to safely encode different parts of a URL.

like image 168
Robby Cornelissen Avatar answered Oct 20 '22 16:10

Robby Cornelissen