MalformedURLException,尽管我已经用%20替换了空格 [英] MalformedURLException although I have already replaced spaces with %20

查看:53
本文介绍了MalformedURLException,尽管我已经用%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");

输出:

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

有人可以帮我吗..

推荐答案

(注意:请参见下面的更新)

使用 URLEncoder 类(来自 java.net 包).空格不是唯一需要在URL中转义的字符,并且 URLEncoder 将确保所有需要编码的字符均已正确编码.

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.

这是一个小例子:

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
}

更新

正如对该问题的评论和其他答案所指出的那样, URLEncoder 类仅可安全地编码URL的查询字符串参数.我目前依靠Guava的 UrlEscapers 安全地编码URL的不同部分.

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.

这篇关于MalformedURLException,尽管我已经用%20替换了空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆