Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.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中是绝对URL还是相对URL_Java_Url - Fatal编程技术网

确定字符串在java中是绝对URL还是相对URL

确定字符串在java中是绝对URL还是相对URL,java,url,Java,Url,给定一个字符串,如何确定它在Java中是绝对URL还是相对URL?我尝试了以下代码: private boolean isAbsoluteURL(String urlString) { boolean result = false; try { URL url = new URL(urlString); String protocol = url.getProtocol();

给定一个字符串,如何确定它在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;
    }

问题是,由于没有定义协议(例如:www.google.com和/questions/ask),所有相关URL都抛出了错误的URL异常。

正如我在评论中所说,在检查URL之前,您必须对URL进行规范化,而规范化取决于您的应用程序,因为
www.google.com
不是绝对URL。下面是一个示例代码,可用于检查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);
  }
}
 private String ensureAbsoluteURL(String base, String maybeRelative) {
    if (maybeRelative.startsWith("http")) {
        return maybeRelative;
    } else {
        try {
           return new URL(new URL(base), maybeRelative).toExternalForm();
        } catch (MalformedURLException e) {
           // do something
        }
    }
}
运行:

~$ 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

这是我用来确保链接绝对的一个片段:

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);
  }
}
 private String ensureAbsoluteURL(String base, String maybeRelative) {
    if (maybeRelative.startsWith("http")) {
        return maybeRelative;
    } else {
        try {
           return new URL(new URL(base), maybeRelative).toExternalForm();
        } catch (MalformedURLException e) {
           // do something
        }
    }
}
那么:

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!");
}
详情请参阅:

这是我做的

public static String processUrl(String urlToProcess, String grantedNormalUrl){
    if (urlToProcess.startsWith("//")){
        urlToProcess = checkUrlStartsWithProtocol(urlToProcess);
        return urlToProcess;
    }

    if (!isAbsolute(urlToProcess)){
        String rootPage = extractRootPage(grantedNormalUrl);
        boolean domainEndsWithSlash = rootPage.endsWith("/");
        boolean urlStartsWithSlash = urlToProcess.startsWith("/");
        if (domainEndsWithSlash && urlStartsWithSlash){
            rootPage = rootPage.substring(0, rootPage.length() - 1); // exclude /
        }
        urlToProcess = rootPage + (!(domainEndsWithSlash || urlStartsWithSlash) ? "/" : "") + urlToProcess;
    }

    return urlToProcess;
}

public static boolean isAbsolute(String url){
    if (url.startsWith("//")) { // //www.domen.com/start
        return true;
    }

    if (url.startsWith("/")){ // /somePage.html
        return false;
    }

    boolean result = false;

    try {
        URI uri = new URI(url);
        result = uri.isAbsolute();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    return result;
}

public static String checkUrlStartsWithProtocol(String url) {
    if (!url.startsWith("http://") && !url.startsWith("https://")) {
        StringBuilder prefixBuilder = new StringBuilder();
        prefixBuilder.append("http:");
        if (!url.startsWith("//")) {
            prefixBuilder.append("//");
        }
        url = prefixBuilder.toString() + url;
    }
    return url;
}

public static String extractRootPage(String urlString) {
    int ignoreSlashes = 0;
    if (urlString.startsWith("http://") || urlString.startsWith("https://")) {
        ignoreSlashes = 2;
    }
    int endPosition = urlString.length();
    for (int i = 0; i < urlString.length(); i++) {
        if (urlString.charAt(i) == '/') {
            if (ignoreSlashes == 0) {
                endPosition = i; //substring exclude /
                break;
            } else {
                ignoreSlashes--;
            }
        }
    }
    return checkUrlStartsWithProtocol(urlString.substring(0, endPosition));
}
publicstaticstringprocessurl(stringurltoprocess,stringgrantednormalurl){
if(urlToProcess.startsWith(“/”){
urlToProcess=checkUrlStartsWithProtocol(urlToProcess);
返回urlToProcess;
}
if(!isAbsolute(urlToProcess)){
字符串rootPage=extractRootPage(grantedNormalUrl);
布尔域endswithslash=rootPage.endsWith(“/”);
布尔值urlStartsWithSlash=urlToProcess.startsWith(“/”);
if(域名swithslash&&urlStartsWithSlash){
rootPage=rootPage.substring(0,rootPage.length()-1);//排除/
}
urlToProcess=rootPage+(!(domainedswithslash | | urlStartsWithSlash)?“/”:”)+urlToProcess;
}
返回urlToProcess;
}
公共静态布尔值(字符串url){
如果(url.startsWith(“//”)为{/////www.domen.com/start
返回true;
}
if(url.startsWith(“/”){///somePage.html
返回false;
}
布尔结果=假;
试一试{
URI=新的URI(url);
结果=uri.isAbsolute();
}捕获(URISyntaxException e){
e、 printStackTrace();
}
返回结果;
}
公共静态字符串checkUrlStartsWithProtocol(字符串url){
如果(!url.startsWith(“http://”)&&!url.startsWith(“https://”)){
StringBuilder prefixBuilder=新StringBuilder();
prefixBuilder.append(“http:”);
如果(!url.startsWith(“/”){
prefixBuilder.append(“/”);
}
url=prefixBuilder.toString()+url;
}
返回url;
}
公共静态字符串extractRootPage(字符串urlString){
int ignoreSlashes=0;
if(urlString.startsWith(“http://”)urlString.startsWith(“https://”){
ignoreSlashes=2;
}
int-endPosition=urlString.length();
for(int i=0;i
。。。因此,捕获异常并返回false,这表明相对URL实际上不是绝对URL;这是预期的结果。那么这是个什么问题呢?“www.google.com”和“/questions/ask”不是URL。它们可能是绝对或相对URI,具体取决于隐含的URL方案。因此,此代码属于“按预期工作”类别。请注意,URL使用您的网络连接
/
文件:
的绝对URL,但它与
http:
相对。如果您不知道基本URL(确切地说,协议),则无法确定给定URL的相对性。在您的示例中-
www.google.com
是一个相对URL,因此在本例中,您的方法是正确的,并且符合规范,但它不能解决您的问题。这似乎不适用于(像//)这样的URL)。您可以使用它来执行绝对重定向,注意您仍然必须处理一个异常:URISyntaxException。这似乎并不困扰OP,但在我的情况下,我更喜欢真正的一行solution@user1075613
URI.create
@Abhijit Sarkar您应该将此作为答案发布(否则我会做:p)我会投您一票!