import java.io.*; import java.net.*; // Program connects to Web server and downloads the specified URL // Thanks to: // Java Examples in a Nutshell by David Flanagan pp.189-191 public class ClientHttp { public static void main(String[] args) { try { if ((args.length != 1) && (args.length != 2)) throw new IllegalArgumentException("Wrong number of arguments"); OutputStream to_stream; if (args.length == 2) { to_stream = new FileOutputStream(args[1]); } else { to_stream = System.out; } URL oururl = new URL(args[0]); // User-specified URL String ourprotocol = oururl.getProtocol(); if (!ourprotocol.equals("http")) throw new IllegalArgumentException("URL must use the 'http:' protocol"); String ourhost = oururl.getHost(); int ourport = oururl.getPort(); if (ourport == -1) ourport = 80; String ourfilename = oururl.getFile(); Socket oursocket = new Socket(ourhost, ourport); InputStream from_ourserver = oursocket.getInputStream(); PrintWriter to_ourserver = new PrintWriter(new OutputStreamWriter(oursocket.getOutputStream())); to_ourserver.println("GET " + ourfilename); to_ourserver.flush(); byte[] ourbuffer = new byte[4096]; int ourbytes_read; while ((ourbytes_read = from_ourserver.read(ourbuffer)) != -1) to_stream.write(ourbuffer, 0, ourbytes_read); oursocket.close(); to_stream.close(); } catch (Exception err) { // Errors System.err.println(err); System.err.println("Usage: java ClientHttp []"); } } }