使用URL提取端口号时出现java问题。URL包含“]”时的getPort()
我正在使用java。网网址。getPort()从URL提取端口号。大多数情况下,这很有效。但是,当URL包含右括号字符“]”时,它将失败:
new URL("http://abc.com:123/abc.mp3").getPort();
returns: (int) 123
但如果URL包含“]”,我会得到:
new URL("http://abc.com:123/abc].mp3").getPort();
returns: (int) -1
我做错了什么
编辑#1:作为测试,我将相同的代码粘贴到一个非Android Java应用程序中,并且正确返回了端口号,因此这似乎是Android SDK的一个异常
# 1 楼答案
如果URL中包含一些在URL中无效的符号,则必须使用URL编码的字符串。他们在Java中实现这一点的方法似乎是使用
URI
如果您已经有URL字符串:
这对我来说很有用:
但我还是用了
url.getPort()
你说没用的。但当我现在在Java 6上测试时new URL("http://abc.com:123/abc].mp3").getPort();
实际上对我有用,也许只是安卓系统不起作用?如果它不起作用,我认为最好使用第三方库。Android中包含的Apache Http客户端似乎有一些额外的URL功能:请参见org.apache.http.client.utils另见HTTP URL Address Encoding in Java
# 2 楼答案
在URI的路径部分不允许使用
]
,因此这不是URL。但是,您可以修改regular expression in the spec以获得以下信息:不管名称如何,
URLEncoder
都不会对URL进行编码。仅当服务器需要application/x-www-form-urlencoded
编码数据时,才应使用它对查询部分中的参数进行编码。URI
和URL
类的行为如文档所示——它们在这里帮不了你# 3 楼答案
下面是一种从可能不同于HTTP的URL(例如JNDI连接URL)中提取端口的更简单方法:
# 4 楼答案
字符串encodedURL=newURI(“http”,null,//abc.com:8080/abc[d].jpg”,null,null)。Toasciisting()
# 5 楼答案
根据RFC1738,
]
字符是不安全的:您应该对要添加的单个字符进行编码,或者通过URL编码器运行整个字符串。试试这个: