有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用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的一个异常


共 (5) 个答案

  1. # 1 楼答案

    如果URL中包含一些在URL中无效的符号,则必须使用URL编码的字符串。他们在Java中实现这一点的方法似乎是使用URI

    new URI( "http", null, "abc.com", 123, "abc].mp3", null, null).toURL().getPort();
    

    如果您已经有URL字符串:

    URL url = new URL("http://abc.com:123/abc].mp3");
    

    这对我来说很有用:

    new URI(
        url.getProtocol(),
        null,
        url.getHost(),
        url.getPort(),
        url.getPath(),
        null,
        null);
    

    但我还是用了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. # 2 楼答案

    "http://abc.com:123/abc].mp3"
    

    在URI的路径部分不允许使用],因此这不是URL。但是,您可以修改regular expression in the spec以获得以下信息:

        //TODO: import java.util.regex.*;
        String expr = "^(([^:/?#]+):)?(//([^:/?#]*):([\\d]*))?";
        Matcher matcher = Pattern.compile(expr)
                                 .matcher("http://abc.com:123/abc].mp3");
        if (matcher.find()) {
          String port = matcher.group(5);
          System.out.println(port);
        }
    

    不管名称如何,URLEncoder都不会对URL进行编码。仅当服务器需要application/x-www-form-urlencoded编码数据时,才应使用它对查询部分中的参数进行编码。URIURL类的行为如文档所示——它们在这里帮不了你

  3. # 3 楼答案

    下面是一种从可能不同于HTTP的URL(例如JNDI连接URL)中提取端口的更简单方法:

    int port = 80; // assumption of default port in the URL
    Pattern p = Pattern.compile(":\\d+"); // look for the first occurrence of colon followed by a number
    Matcher matcher = p.matcher(urlSrtr);
    if (matcher.find()) {
        String portStrWithColon = matcher.group();
        if (portStrWithColon.length() > 1) {
            String portStr = portStrWithColon.substring(1);
            try {
                port = Integer.parseInt(portStr);
            } catch (NumberFormatException e) {
                // handle
            }
        }
    }
    return port;
    
  4. # 4 楼答案

    字符串encodedURL=newURI(“http”,null,//abc.com:8080/abc[d].jpg”,null,null)。Toasciisting()

  5. # 5 楼答案

    根据RFC1738]字符是不安全的:

    Other characters are unsafe because gateways and other transport agents are known to sometimes modify such characters. These characters are "{", "}", "|", "\", "^", "~", "[", "]", and "`".

    Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.

    您应该对要添加的单个字符进行编码,或者通过URL编码器运行整个字符串。试试这个:

    new URL("http://abc.com:123/abc%5D.mp3").getPort();