Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...