确定字符串是否是java中的绝对URL或相对URL

kha*_*lsa 25 java url

给定一个字符串,如何确定它是Java中的绝对URL还是相对URL?我尝试了以下代码:

private boolean isAbsoluteURL(String urlString)
    {
        boolean result = false;
        try
        {
            URL url = new URL(urlString);
            String protocol = url.getProtocol();
            if (protocol != null && protocol.trim().length() > 0)
                result = true;
        }
        catch (MalformedURLException e)
        {
            return false;
        }
        return result;
    }
Run Code Online (Sandbox Code Playgroud)

问题是所有相对URL都抛出了MalformedURLException,因为没有定义协议(例如:www.google.com和/ questions/ask).

Chr*_*ris 43

怎么样:

final URI u = new URI("http://www.anigota.com/start");
// URI u = new URI("/works/with/me/too");
// URI u = new URI("/can/../do/./more/../sophis?ticated=stuff+too");

if(u.isAbsolute())
{
  System.out.println("Yes, i am absolute!");
}
else
{
  System.out.println("Ohh noes, it's a relative URI!");
}
Run Code Online (Sandbox Code Playgroud)

详情请见:http://docs.oracle.com/javase/7/docs/api/java/net/URI.html

HTH

  • 这似乎不适用于[协议网址](http://www.paulirish.com/2010/the-protocol-relative-url/)(网址类似于//).你可以[在IDEOne试试](http://ideone.com/9AlUkU) (5认同)

kha*_*hik 4

正如我在评论中所说,您必须在检查 URL 之前对其进行规范化,并且规范化取决于您的应用程序,因为www.google.com它不是绝对 URL。下面是一个示例代码,可用于检查 URL 是否绝对:

import java.net.URL;

public class Test {
  public static void main(String [] args) throws Exception {
    String [] urls = {"www.google.com",
                      "http://www.google.com",
                      "/search",
                      "file:/dir/file",
                      "file://localhost/dir/file",
                      "file:///dir/file"};
    
    for (String url : urls) {
      System.out.println("`" + url + "' is " + 
                          (isAbsoluteURL(url)?"absolute":"relative"));
    }
  }

  public static boolean isAbsoluteURL(String url)
                          throws java.net.MalformedURLException {
    final URL baseHTTP = new URL("http://example.com");
    final URL baseFILE = new URL("file:///");
    URL frelative = new URL(baseFILE, url);
    URL hrelative = new URL(baseHTTP, url);
    System.err.println("DEBUG: file URL: " + frelative.toString());
    System.err.println("DEBUG: http URL: " + hrelative.toString());
    return frelative.equals(hrelative);
  }
}
Run Code Online (Sandbox Code Playgroud)

输出:

~$ java Test 2>/dev/null
`www.google.com' is relative
`http://www.google.com' is absolute
`/search' is relative
`file:/dir/file' is absolute
`file://localhost/dir/file' is absolute
`file:///dir/file' is absolute
Run Code Online (Sandbox Code Playgroud)