在java中用%20替换空格 [英] Replacing spaces with %20 in java

查看:2009
本文介绍了在java中用%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

但我收到错误消息:

java.net.MalformedURLException: Illegal character in URL

有人可以帮助我..

推荐答案

(注:请参阅下面的更新)

使用 URLEncoder class来自 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 class只能安全地编码URL的查询字符串参数。我目前依赖于Guava的 UrlEscapers 可安全地对网址的不同部分进行编码。

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.

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

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