我希望能够获取网页的html并将其保存到String,以便可以对其进行一些处理。另外,我该如何处理各种类型的压缩。

我将如何使用Java做到这一点?

最佳答案

这是一些使用Java的URL类测试过的代码。我建议比在这里处理异常或将异常传递到调用堆栈方面做得更好。

public static void main(String[] args) {
    URL url;
    InputStream is = null;
    BufferedReader br;
    String line;

    try {
        url = new URL("http://stackoverflow.com/");
        is = url.openStream();  // throws an IOException
        br = new BufferedReader(new InputStreamReader(is));

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (MalformedURLException mue) {
         mue.printStackTrace();
    } catch (IOException ioe) {
         ioe.printStackTrace();
    } finally {
        try {
            if (is != null) is.close();
        } catch (IOException ioe) {
            // nothing to see here
        }
    }
}

10-08 13:31
查看更多