How to fetch HTML in Java

pek picture pek · Aug 28, 2008 · Viewed 61k times · Source

Without the use of any external library, what is the simplest way to fetch a website's HTML content into a String?

Answer

pek picture pek · Aug 28, 2008

I'm currently using this:

String content = null;
URLConnection connection = null;
try {
  connection =  new URL("http://www.google.com").openConnection();
  Scanner scanner = new Scanner(connection.getInputStream());
  scanner.useDelimiter("\\Z");
  content = scanner.next();
  scanner.close();
}catch ( Exception ex ) {
    ex.printStackTrace();
}
System.out.println(content);

But not sure if there's a better way.