Reputation: 207
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 ..
Upvotes: 19
Views: 57406
Reputation: 87
java.net.URLEncoder.encode("Hello World", "UTF-8").replaceAll("\\+", "%20"));
have a nice day =).
Upvotes: 4
Reputation: 97120
(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.
Upvotes: 17
Reputation: 3578
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.
Upvotes: 6
Reputation: 6479
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:
See URLEncoder
Ex:
String url = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + URLEncoder.encode(origin, "UTF-8");
Upvotes: 11