javaioinputstreambufferedreaderinputstreamreader

Having trouble reading in content of url using InputStream


So I run the code below and it prints "!DOCTYPE html". How do I get the content of the url, like the html for instance?

public static void main(String[] args) throws IOException {
        URL u = new URL("https://www.whitehouse.gov/");
        InputStream ins = u.openStream();
        InputStreamReader isr = new InputStreamReader(ins);
        BufferedReader websiteText = new BufferedReader(isr);
        System.out.println(websiteText.readLine());

    }

According to java doc https://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html: "When you run the program, you should see, scrolling by in your command window, the HTML commands and textual content from the HTML file located at ".... Why am I not getting that?


Solution

  • In your program, your did not put while loop.

       URL u = new URL("https://www.whitehouse.gov/");
        InputStream ins = u.openStream();
        InputStreamReader isr = new InputStreamReader(ins);
        BufferedReader websiteText = new BufferedReader(isr);
        String inputLine;
        while ((inputLine = websiteText.readLine()) != null){
            System.out.println(inputLine);
       }
    
      websiteText.close();