Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

java - MalformedURLException although I have already replaced spaces with %20

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...