有 Java 编程相关的问题?

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

确定请求URI是否在另一个URL内的快速java例程

在一个类(Java8)中,我有一个表示HTTP URL的字符串,例如String str1="http://www.foo.com/bar",还有一个包含请求URI的字符串,例如str2="/bar/wonky/wonky.html"

在代码执行方面,确定str2是否在str1的上下文中(例如,上下文是/bar),然后构造完整的urlString result = "http://www.foo.com/bar/wonky/wonky.html"的最快方法是什么


共 (1) 个答案

  1. # 1 楼答案

    我不知道是否有更快的方法来使用String.indexOf()。下面是一种方法,我认为它涵盖了您给出的示例(demo):

      public static boolean overlap(String a, String b_context) {
        //Assume the a URL starts with http:// or https://, the next / is the start of the a_context
        int root_index = a.indexOf("/", 8);
        String a_context = a.substring(root_index);
        String a_host = a.substring(0, root_index);
        return b_context.startsWith(a_context);
      }
    

    这是一个使用相同逻辑的函数,但如果两个URL重叠,则将它们组合在一起;如果两个URL不重叠,则引发异常

      public static String combine(String a, String b_context) {
        //Assume the a URL starts with http:// or https://, the next / is the start of the a_context
        int root_index = a.indexOf("/", 8);
        String a_context = a.substring(root_index);
        String a_host = a.substring(0, root_index);
        if(b_context.startsWith(a_context)) {
          return a_host + b_context;
        } else {
          throw new RuntimeException("urls do not overlap");
        }
      }
    

    下面是一个使用它们的例子

      public static void main(String ... args) {
        System.out.println(combine("http://google.com/search", "/search?query=Java+String+Combine"));
        System.out.println(combine("http://google.com/search", "/mail?inbox=Larry+Page"));
      }