Java如何确定URL是http还是https?

时间:2014-03-27 00:05:37

标签: java url jsoup web-crawler

我正在用Java编写一个Web爬虫工具。当我输入网站名称时,如何在不定义协议的情况下将其连接到http或https中的该网站?

try {
   Jsoup.connect("google.com").get();
} catch (IOException ex) {
   Logger.getLogger(LinkGUI.class.getName()).log(Level.SEVERE, null, ex);
}

但我收到错误:

java.lang.IllegalArgumentException: Malformed URL: google.com

我该怎么办?是否有任何类或库可以做到这一点?

我想要做的是我有165个课程的列表,每个课程有65-71个html页面,其中包含所有链接。我正在编写一个Java程序来测试链接是否损坏。

1 个答案:

答案 0 :(得分:1)

您可以编写自己的简单方法来尝试这两种协议,例如:

static boolean usesHttps(final String urlWithoutProtocol) throws IOException {
    try {
        Jsoup.connect("http://" + urlWithoutProtocol).get();
        return false;
    } catch (final IOException e) {
        Jsoup.connect("https://" + urlWithoutProtocol).get();
        return true;
    }
}

然后,您的原始代码可以是:

try {
    boolean shouldUseHttps = usesHttps("google.com");
} catch (final IOException ex) {
    Logger.getLogger(LinkGUI.class.getName()).log(Level.SEVERE, null, ex);
}

注意:您应该只使用每个URL的usesHttps()方法一次来确定要使用的协议。在您知道之后,您应该直接使用Jsoup.connect()进行连接。这样会更有效率。

相关问题