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

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

本文介绍了确定字符串是否是java中的绝对URL或相对URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Given a string, how do I determine if it is absolute URL or relative URL in Java? I tried the following code:

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;
    }

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

The problem is that all relative URLs are throwing the MalformedURLException as there is no protocol defined (example: www.google.com and /questions/ask).

推荐答案

如何:

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!");
}

详情请见:

HTH

这篇关于确定字符串是否是java中的绝对URL或相对URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:40