This example implements a getPage method. It takes a file from a remote address and places it into a new String. There are some complexities in getPage.
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URI;
public class Program {
public static String getPage(String address) throws IOException, URISyntaxException {
// Get URI and URL objects.
URI uri = new URI(address);
URL url = uri.toURL();
// Get stream of the response.
InputStream in = url.openStream();
// Store results in StringBuilder.
StringBuilder builder = new StringBuilder();
byte[] data = new byte[1024];
// Read in the response into the buffer.
// ... Read many bytes each iteration.
int c;
while ((c = in.read(data, 0, 1024)) != -1) {
builder.append(new String(data, 0, c));
}
// Return String.
return builder.toString();
}
public static void main(String[] args) {
try {
String page = getPage(
"http://www.example.com/");
System.out.println(page);
} catch (Exception ex) {
System.out.println(
"ERROR");
}
}
}
<!doctype html>
<html>
<head>
<title>Example Domain</title>
<meta charset=
"utf-8" />