在Java中,读取URL并将其拆分成几部分的最佳方法是什么? [英] In java, what's the best way to read a url and split it into its parts?

查看:79
本文介绍了在Java中,读取URL并将其拆分成几部分的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我知道还有其他类似的帖子,但是由于我使用的是URL,而且我并不总是确定分隔符是什么,因此我认为可以发问.我的任务是制作一个粗糙的Web浏览器.我有一个textField,用户可以在其中输入所需的URL.然后,我显然必须导航到该网页.这是我老师的一个例子,说明我的代码看起来像什么.这是我应该发送到我的套接字的代码.样本网址: http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol

Firstly, I am aware that there are other posts similar, but since mine is using a URL and I am not always sure what my delimiter will be, I feel that I am alright posting my question. My assignment is to make a crude web browser. I have a textField that a user enters the desired URL into. I then have obviously have to navigate to that webpage. Here is an example from my teacher of what my code would look kinda like. This is the code i'm suposed to be sending to my socket. Sample 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"部分以及扩展名呢?我尝试将其作为测试:

So my question is this: I am going to read in the url as just one complete string, so how do I extract just the "en.wikipedia.org" part and just the extension? I tried this as a test:

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

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

This just prints out the URL without the ".org" in it. I think i'm on the right track. I am just not sure. Also, I know that websites can have different endings (.org, .com, .edu, etc) so I am assuming i'll have to have a few if statements that compenstate for the possible different endings. Basically, how do I get the url into the two parts that I need?

推荐答案

URL 类几乎可以做到这一点,请查看教程.例如,给定以下URL:

The URL class pretty much does this, look at the tutorial. For example, given this URL:

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

这是您可以期望获得的信息:

This is the kind of information you can expect to obtain:

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

这篇关于在Java中,读取URL并将其拆分成几部分的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆