/** * 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 Java using pre-1.5 * 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://cs.carleton.edu/faculty/jondich/courses/cs257_s07/index.html"; System.out.print( retrievePageViaInputStream( urlString ) ); System.out.println( "\n==========================================\n" ); System.out.print( retrievePageViaScanner( urlString ) ); } public static String retrievePageViaInputStream( String urlString ) { String resultString = ""; try { URL url = new URL( urlString ); InputStream in = url.openStream(); int ch; while( (ch=in.read()) != -1 ) resultString += (char)ch; } catch( MalformedURLException e ) { System.err.println( "Bad URL format: " + e.getMessage() ); } catch( IOException e ) { System.err.println( "No such URL: " + e.getMessage() ); } return resultString; } public static String retrievePageViaScanner( String urlString ) { String resultString = ""; try { URL url = new URL( urlString ); Scanner in = new Scanner( url.openStream() ); while( in.hasNextLine() ) { resultString += in.nextLine(); resultString += '\n'; } } catch( MalformedURLException e ) { System.err.println( "Bad URL format: " + e.getMessage() ); } catch( IOException e ) { System.err.println( "No such URL: " + e.getMessage() ); } return resultString; } }