代码之家  ›  专栏  ›  技术社区  ›  sixtyfootersdude

Java:url.openStream()的文件类型`

  •  2
  • sixtyfootersdude  · 技术社区  · 14 年前

    我写这个方法是为了下载一个给定网址的网页。它是专为下载HTML而设计的。如果我想做错误检查并且只允许HTML,我应该怎么做?

    public static String download(URL url) throws IOException {
        InputStream is = url.openStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String page = "";
        String line;    
        while((line = reader.readLine()) != null){
            page = page + line;
        }
        return page;
    }
    

    最初我打算这么做:

    String file = url.getFile();
    if(file.subString(file.indexOf("."),file.length()-1).equalsIgnoreCase("HTML")){
        // do method
    

    但是,网址: http://www.smu.com 回报 "" 对于 url.getFile() . 有人有什么建议吗?

    3 回复  |  直到 14 年前
        1
  •  4
  •   Community paulsm4    7 年前

    若要测试是否获取html,可以使用URL.openConnection()获取UrlConnection,然后调用getContentType(),该函数应返回html页面的“text/html”。然后可以在UrlConnection()上使用getInputStream()方法作为url.openStream()的替换项;

    需要考虑的是,许多网站将根据HTTP连接上发送的用户代理字符串提供不同的数据,这可能是www.smu.com不返回数据的原因。您可能需要在UrlConnection上使用:UrlConnection.addRequestProperty(“用户代理”,…);查看更多信息: Setting user agent of a java URLConnection

        2
  •  3
  •   Brian Agnew    14 年前

    如果你想检查内容 超过 Content-Type header,然后可以使用HTML解析器,例如(错误命名的!) JTidy .

        3
  •  2
  •   user166390 user166390    14 年前

    “http://www.smu.com”向您发送“http://www.smu.com/index.html”中的数据。这是请求“/”时web服务器的(常见)行为(理论上,web服务器还可以使用302或其他命令重定向)。因此,检查URL是否以“.html”结尾完全是愚蠢的(更不用说它可能是“.php”、“.asp”或其他东西)。

    但是,a 美好的 提供HTML的web服务器应返回 Content-Type

    你可能会想用 URLConnection . 这是一个 example of URLConnection with headers .

    我跑了 curl -I http://www.smu.com (和../index.html)并比较结果。它们看起来像:

    HTTP/1.1 200 OK
    Date: Tue, 19 Oct 2010 18:01:39 GMT
    Server: Apache
    Last-Modified: Wed, 27 Jan 2010 20:27:52 GMT
    Accept-Ranges: bytes
    Content-Length: 2993
    Content-Type: text/html