19
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 ..

oberlies
  • 11,503
  • 4
  • 63
  • 110
user3742241
  • 207
  • 1
  • 2
  • 4
  • I used the marked answer in this [SO question](https://stackoverflow.com/questions/4737841/urlencoder-not-able-to-translate-space-character). I hope it works for you. – Jendorski Labs Jul 15 '18 at 20:57
  • Just paste the resulting URL into any URL validator? IMHO you should have done this before asking on StackOverflow. – oberlies May 03 '19 at 13:31

5 Answers5

17

(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.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • 8
    This doesn't actually work. UrlEncoder encodes spaces as "+", which is acceptable for the query part of a URL, but not for the path part. See https://web.archive.org/web/20151218094722/http://blog.lunatech.com/2009/02/03/what-every-web-developer-must-know-about-url-encoding#Thereservedcharactersaredifferentforeachpart – aij Oct 05 '16 at 15:23
11

You shouldn't call String.replaceAll to encode an URL, instead you should use java.net.URLEncoder.encode(String s, String enc).

Note that you only need to encode the query string parameters (name and value) and not the entire URL.

When encoding a String using java.net.URLEncoder.encode(String s, String enc), the following rules apply:

  • The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the same.
  • The special characters ".", "-", "*", and "_" remain the same.
  • The space character " " is converted into a plus sign "+".
  • All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the
    platform is used.

See URLEncoder

Ex:

String url = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + URLEncoder.encode(origin, "UTF-8");
M. Abbas
  • 6,409
  • 4
  • 33
  • 46
  • 5
    This did not solve my problem, I tried using URLEncoder and my url looked like this : http%3A%2F%2Fmaps.googleapis.com%2Fmaps%2Fapi%2Fdistancematrix%2Fxml%3Forigins%3D150+Sutter+St+San+Francisco%2C+CA%2C+United+States%26destinations%3D410+Eddy+St%0AIthaca%2C+NY+14850%26mode%3Ddriving%26sensor%3Dfalse%26language%3Den-EN%26units%3Dimperial – user3742241 Jun 16 '14 at 17:35
  • 4
    @user3742241 you only need to encode the query string parameters (name and value) and not the entire URL. – M. Abbas Jun 16 '14 at 19:41
6

Here is the answer which helped me: HTTP URL Address Encoding in Java

Its just using URL & URI objects.

Original aproach mentioned above in this thread with URLEncoder, encoded all characters in url including http:// and using such url was throwing exception in httpConnection - therefore its not a good option. I am now using URL/URI approach mentioned in link, and it's working as expected.

Community
  • 1
  • 1
To Kra
  • 3,344
  • 3
  • 38
  • 45
4

java.net.URLEncoder.encode("Hello World", "UTF-8").replaceAll("\\+", "%20"));have a nice day =).

Pregunton
  • 77
  • 7
1

Try

str.replaceAll("\\s","%20");

That should fix it

Zoe
  • 27,060
  • 21
  • 118
  • 148