如何只解析域名

时间:2013-07-15 17:50:09

标签: java

我想在JAVA中只解析域名。 例如,

http://facebook.com/bartsf
http://www.facebook.com/pages/Shine-Communications/169790283042195
http://graph.facebook.com/100002306245454/picture?width=150&height=150
http://maps.google.com/maps?hl=en&q=37.78353+-122.39579
http://www.google.com/url?sa=X&q=http://www.onlinehaendler-news.de/interviews/1303-abba24-im-spagat-zwischen-haendler-und-kaeuferinteressen.html&ct=ga&cad=CAEQARgAIAAoATABOAFAnqSQjwVIAVAAWABiAmRl&cd=xa_cHWHNG70&usg=AFQjCNFMgnkzqN0fNKMFKz1NTKK1n9Gg9A

这是我的代码我正在编写map reduce代码。

 String[] whiteList={"www.facebook.com","www.google.com"};
 UrlValidator urlValidator=new UrlValidator(schemes);
 Readfile line by line

for line in file
{
            String sCurrentLine=line;
            if(sCurrentLine.length()>=3)
            {
                String tempString=sCurrentLine.substring(0,3);

                if(!tempString.equals("192") && !tempString.equals("172") && !tempString.equals("10."))
                {

                    sCurrentLine="http://"+sCurrentLine;
                    if(urlValidator.isValid(sCurrentLine))//domain filter should be here
                    {
                           System.out.println(sCurrentLine);
                    }
                }
                tempString="";
            }
 }

我想过滤域名是facebook.com还是google.com,以上所有网址都被过滤掉了。

2 个答案:

答案 0 :(得分:8)

使用java.net.URI将字符串解析为URI。这里没有必要重新发明轮子。

URI foo = new URI("http://facebook.com/bartsf");
String host = foo.getHost(); // "facebook.com"

答案 1 :(得分:2)

或者您可以使用URL类:

URL url = new URL("http://www.facebook.com/pages/Shine-Communications/169790283042195");
String host = url.getHost();
// 'indexOf' is required since the root domain is all you care about. This handles
//  bob.facebook.com as well as facebook.com 
if (host.indexOf("facebook.com") >= 0 || host.indexOf("google.com") >= 0) {
    ... got one of those ...
} else {
    ... got something else ...
}

您必须添加一些try ... catch内容来处理传递给URL构造函数的字符串,而这些构造函数可能根本不是URL。

此外,请注意,如果您将问题传递给file://mailto:,这可能无法完全符合您的要求。

我在使用这个类时遇到的最大问题是javadocs中没有任何地方定义所有术语。例如,路径是什么?它由方法getPath()返回,该方法有javadoc说“获取此URL的路径部分”。你可能想知道究竟是什么包括在内。我想知道在?#之前是否包含了网址的最后部分。 (答案是否定的。它只是在?#或URL结尾之前的最后一个斜杠。)

继续问题扩展

我不喜欢这句话:

String tempString=sCurrentLine.substring(0,3);
if (!tempString.equals("192") && !tempString.equals("172") && !tempString.equals("10."))

但我确实喜欢这个:

if(!sCurrentLine.startsWith("192.168.") && !sCurrentLine.beginsWith("172.") && !sCurrentLine.startsWith("10."))

我怀疑如果你的白名单只有'facebook.com'和'google.com'会更好,因为'www'不是那么重要,而且两家公司都有很多子域名。

上面的代码会出现在UrlValidator课程中。