/** * HTTPGet.java * * @author Jeff Ondich * @version 5/11/05 * * This is a simple example of one way to retrieve a web file's source. * This program retrieves the same file twice--once using the raw * InputStream returned by URL.openStream, and once using a Scanner * object based on that InputStream. For people using pre-1.5 (on Macs, * for example), you might want to investigate BufferedReader approaches * to taking input from the InputStream. */ import java.io.*; import java.util.*; import java.net.*; class HTTPGet { public static void main( String[] args ) { String urlString = "http://www.mathcs.carleton.edu/faculty/jondich/cs257/index.html"; retrievePageViaInputStream( urlString ); System.out.println( "\n==========================================\n" ); retrievePageViaScanner( urlString ); } public static void retrievePageViaInputStream( String urlString ) { try { URL url = new URL( urlString ); InputStream in = url.openStream(); int ch; while( (ch=in.read()) != -1 ) System.out.print( (char)ch ); } catch( MalformedURLException e ) { System.err.println( "Bad URL format: " + e.getMessage() ); } catch( IOException e ) { System.err.println( "No such URL: " + e.getMessage() ); } } public static void retrievePageViaScanner( String urlString ) { try { URL url = new URL( urlString ); Scanner in = new Scanner( url.openStream() ); while( in.hasNextLine() ) System.out.println( in.nextLine() ); } catch( MalformedURLException e ) { System.err.println( "Bad URL format: " + e.getMessage() ); } catch( IOException e ) { System.err.println( "No such URL: " + e.getMessage() ); } } }