且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

你如何以编程方式下载 Java 网页

更新时间:2023-02-12 19:19:23

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

Here's some tested code using Java's URL class. I'd recommend do a better job than I do here of handling the exceptions or passing them up the call stack, though.

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

    try {
        url = new URL("http://***.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
        }
    }
}