在Java中,读取URL并将其拆分为各个部分的最佳方法是什么?

12
首先,我知道有其他类似的帖子,但由于我的使用URL,并且我不总是确定我的分隔符将是什么,所以我认为我可以发布我的问题。我的任务是制作一个简单的Web浏览器。我有一个文本字段,用户输入所需的URL。然后,我显然必须导航到该网页。这是我的老师提供的一个示例,展示了我的代码应该看起来像什么。这是我应该发送到我的套接字的代码。示例URL:http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
 GET /wiki/Hypertext_Transfer_Protocol HTTP/1.1\n
Host: en.wikipedia.org\n
\n

所以我的问题是:我将整个url作为一个完整的字符串输入,那么如何提取“en.wikipedia.org”部分和扩展名?我尝试了以下代码作为测试:
 String url = "http://en.wikipedia.org/wiki/Hypertext Transfer Protocol";
    String done = " ";
    String[] hope = url.split(".org");

    for ( int i = 0; i < hope.length; i++)
    {
        done = done + hope[i];
    }
    System.out.println(done);

这只是打印出URL,不包含“.org”部分。我认为我走在正确的道路上,但我不确定。此外,我知道网站可以有不同的结尾(.org、.com、.edu等),所以我假设我需要一些if语句来弥补可能的不同结尾。基本上,我如何将URL分成我需要的两个部分?


一些来自 https://dev59.com/HWYr5IYBdhLWcg3wi6zd 的答案也是适用的。 - Ilya Serbis
5个回答

46

URL类基本上就是这么做的,看一下tutorial。例如,给定此URL:

http://example.com:80/docs/books/tutorial/index.html?name=networking#DOWNLOADING

这是您可以期望获得的信息类型:
protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING

2
太棒了!谢谢。我真的需要更好地了解我的类。 - art3m1sm00n
@GabrielleLee 不用谢!如果这个答案对你有帮助,请别忘了点击左边的勾号接受它 ;) - Óscar López

1
尽管URL类的答案很好,这里还有一种使用正则表达式将URL分割成组件的方法:
"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"
      ||            |  |          |       |   |        | |
      12 - scheme   |  |          |       |   |        | |
                    3  4 - authority, includes hostname/ip and port number.
                                  5 - path|   |        | |
                                          6   7 - query| |
                                                       8 9 - fragment

您可以使用Pattern类来操作它:
var regex = "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
var pattern = Pattern.compile(REGEX);
var matcher = pattern.matcher("http://example.com:80/docs/books/tutorial/index.html?name=networking#DOWNLOADING");
if (matcher.matches()) {
  System.out.println("scheme: " + matcher.group(2));
  System.out.println("authority: " + matcher.group(4));
  System.out.println("path: " + matcher.group(5));
  System.out.println("query: " + matcher.group(7));
  System.out.println("fragment: " + matcher.group(9));
}

1

1

尝试使用url.split("/");并迭代您的字符串数组,而不是url.split(".org");

或者您可以研究正则表达式。 这是一个不错的例子

祝你的作业好运。


请使用专门设计的URL。它将处理许多简单分割或正则表达式难以处理的边缘情况。 - Mikezx6r

-1
你可以使用String类的split()方法将结果存储到String数组中,然后遍历数组并将变量和值存储到Map中。
public class URLSPlit {
    public static Map<String,String> splitString(String s) {
        String[] split = s.split("[= & ?]+");
        int length = split.length;
        Map<String, String> maps = new HashMap<>();

        for (int i=0; i<length; i+=2){
              maps.put(split[i], split[i+1]);
        }

        return maps;
    }

    public static void main(String[] args) {
        String word = "q=java+online+compiler&rlz=1C1GCEA_enIN816IN816&oq=java+online+compiler&aqs=chrome..69i57j69i60.18920j0j1&sourceid=chrome&ie=UTF-8?k1=v1";
        Map<String, String> newmap =  splitString(word);

        for(Map.Entry map: newmap.entrySet()){
            System.out.println(map.getKey()+"  =  "+map.getValue());
        }
    }
}

请使用专门设计的URL。它将处理许多简单分割或正则表达式难以处理的边缘情况。 - Mikezx6r

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接