Java GET Using java.net

Here’s a simple code snippet showing how to fetch the contents of a URL. The URL to fetch is in the string url_string , and html stores the contents of the fetched file.

URL url = new URL(url_string);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String html = "";
String line = "";
while ((line = reader.readLine()) != null) {
    html += line;
}
reader.close();

This code may throw a java.io.IOException if an error is encountered while fetching the URL.

This code requires the below imports:

import java.net.URL;
import java.io.InputStreamReader;
import java.io.BufferedReader;