How do you Programmatically Download a Webpage in Java

前端 未结 11 2164
无人共我
无人共我 2020-11-22 11:20

I would like to be able to fetch a web page\'s html and save it to a String, so I can do some processing on it. Also, how could I handle various types of compr

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 12:02

    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://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
            }
        }
    }
    

提交回复
热议问题