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 ..
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.
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.
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With