Java Notes

Read page from Web server

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
// Original: Adapted from the 1997 Java Tutorial by Fred Swartz 
//           to use Scanner classes.  April 2007
// Description: Demo reading web page text lines by printing them.

import java.net.*;
import java.io.*; 
import java.util.Scanner;

class ReadURL2 { 
    public static void main(String[] notUsed) { 
        try { 
            URL yahooURL = new URL("http://www.yahoo.com/"); 
            Scanner in = new Scanner(yahooURL.openStream());
            
            while (in.hasNextLine()) { 
                String line = in.nextLine();
                System.out.println(line); // Just print it.
            } 
            in.close(); 
    
        } catch (MalformedURLException me) { 
            System.err.println(me); 
    
        } catch (IOException ioe) { 
            System.err.println(ioe); 
        } 
    }
}

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 yahooURL = new URL("http://www.yahoo.com/"); 
  URLConnection yahooConnection = yahooURL.openConnection(); 
  Scanner in = new Scanner(yahooConnection.openStream());

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.

References