在java中,读取url并将其拆分为部分的最佳方法是什么?

art*_*00n 6 java string url split

首先,我知道还有其他类似的帖子,但由于我使用的是URL,而且我并不总是确定我的分隔符是什么,我觉得我可以发布我的问题.我的任务是制作一个原始的Web浏览器.我有一个textField,用户输入所需的URL.然后,我显然必须导航到该网页.这是我老师对我的代码看起来有点像的一个例子.这是我要发送到我的套接字的代码.示例网址:http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol

 GET /wiki/Hypertext_Transfer_Protocol HTTP/1.1\n
Host: en.wikipedia.org\n
\n
Run Code Online (Sandbox Code Playgroud)

所以我的问题是这样的:我将在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);
Run Code Online (Sandbox Code Playgroud)

这只是打印出没有".org"的URL.我想我走在正确的轨道上.我只是不确定.另外,我知道网站可以有不同的结尾(.org,.com,.edu等),所以我假设我必须有一些if语句来补充可能的不同结局.基本上,我如何将url放入我需要的两个部分?

Ósc*_*pez 33

URL类几乎做到这一点,看看教程.例如,给定此URL:

http://example.com:80/docs/books/tutorial/index.html?name=networking#DOWNLOADING
Run Code Online (Sandbox Code Playgroud)

这是您可以获得的信息:

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
Run Code Online (Sandbox Code Playgroud)

  • 真棒!谢谢.我真的需要更好地了解我的课程 (2认同)