Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 虽然我已将空格替换为%20,但格式异常_Java_Url - Fatal编程技术网

Java 虽然我已将空格替换为%20,但格式异常

Java 虽然我已将空格替换为%20,但格式异常,java,url,Java,Url,输出: http://maps.googleapis.com/maps/api/distancematrix/xml?origins=150%20Sutter%20St%20San%20Francisco,%20CA,%20United%20States&destinations=1%20Palmer%20Sq%20E 普林斯顿,%20NJ%2008542&模式=驾驶&传感器=错误&语言=英语&单位=英制 但我得到了一个错误,说: String url = "http://maps.googl

输出:

http://maps.googleapis.com/maps/api/distancematrix/xml?origins=150%20Sutter%20St%20San%20Francisco,%20CA,%20United%20States&destinations=1%20Palmer%20Sq%20E
普林斯顿,%20NJ%2008542&模式=驾驶&传感器=错误&语言=英语&单位=英制
但我得到了一个错误,说:

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");
有人能帮我吗?

(注意:见下面的更新)

使用
java.net
包中的类。空格不是URL中需要转义的唯一字符,
urlcoder
将确保所有需要编码的字符都正确编码

下面是一个小例子:

java.net.MalformedURLException: Illegal character in URL
更新


正如在对这个问题的评论和其他回答中指出的那样,
urlcoder
类只对URL的查询字符串参数进行编码是安全的。我目前依靠Guava对URL的不同部分进行安全编码。

您不应该调用
String.replaceAll
对URL进行编码,而应该使用
java.net.URLEncoder.encode(String s,String enc)

请注意,您只需要对查询字符串参数(名称和值)进行编码,而不需要对整个URL进行编码

使用
java.net.URLEncoder.encode(String s,String enc)
对字符串进行编码时,以下规则适用:

  • 字母数字字符“a”到“z”、“a”到“z”和“0” 通过“9”保持不变
  • 特殊字符“.”、“-”和“*”保持不变
  • 空格字符“”被转换为加号“+”
  • 所有其他字符都是不安全的,首先转换为一个字符 一个或多个字节使用某种编码方案。然后每个字节都是 由3个字符的字符串“%xy”表示,其中xy是 字节的两位十六进制表示形式。建议使用的编码方案是UTF-8。但是,出于兼容性的原因, 如果未指定编码,则默认编码为
    使用平台

例:


以下是帮助我的答案:

它只是使用
URL
URI
对象


这个线程中提到的原始方法是使用
urlcoder
,对url中的所有字符进行编码,包括
http://
,使用这样的
url
会在
httpConnection
中引发
异常
——因此这不是一个好的选择。我现在使用的是链接中提到的
URL/URI
方法,它工作正常。

java.net.URLEncoder.encode(“Hello World”,“UTF-8”).replaceAll(“\\+”,“%20”)祝你今天愉快=)。

试试看

String url = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + URLEncoder.encode(origin, "UTF-8");

这应该可以解决它

这并没有解决我的问题,我尝试使用URLEncoder,我的url如下:http%3A%2F%2Fmaps.googleapis.com%2Fmaps%2Fapi%2fdancematrix%2Fxml%3Forigins%3D150+Sutter+St+San+Francisco%2C+CA%2C+美国%26目的地%3D410+Eddy+St%0AIthaca%2C+NY+14850%26模式%3driving%26传感器%3dflse%26语言%3Den%26单位%26%3Dimperial@user3742241你只需要编码查询字符串参数(名称和值)而不是整个URL。这实际上不起作用。UrlEncoder将空格编码为“+”,这对于URL的查询部分是可接受的,但对于路径部分则不是。看看如果他们有一个合法的
+
?嗨,你有一个例子吗?最好用%20代替空格,对吗。当我这样做的时候,我得到了
Hello%2520World
我在这里使用了标记的答案。我希望它对你有用。只需将结果URL粘贴到任何URL验证程序中?在询问StackOverflow之前,我想你应该怎么做。
String url = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + URLEncoder.encode(origin, "UTF-8");
str.replaceAll("\\s","%20");