Java: Read page from Web server
/* This program was taken from the Java Tutorial
http://java.sun.com/docs/books/tutorial/networking/urls/readingURL.html
Modified by Fred Swartz to use the Java 1.1 "Reader" classes. 24 Nov 1997
*/
import java.net.*;
import java.io.*;
class ReadURL {
public static void main(String[] args) {
try {
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
// Process each line.
System.out.println(inputLine);
}
in.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
}//end main
}//end class ReadURL
Another way to read from a server
It's possible to have more control over the connection by using
the URLConnection, or HttpURLConnection classes. For example, using a URLConnection
object is very similar to the above example.
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yahooConnection = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(yahooConnection.getInputStream()));
Lower-level network I/O
Java network I/O is at the level to UPD, TCP, and higher-level protocols
(HTTP, SMTP, ...). It is not possible to do network I/O at the very
low levels (eg, ICMP), but this is not a problem for any normal programs.
However, there are a few programs
(like ping and traceroute) that you can not write in Java.