import java.io.*;
import java.net.*;

public class GetWebPage {

  public static void main (String args[])
      throws IOException, UnknownHostException {
    String resource, host, file;
    int slashPos;

    if (args.length != 1) {
      System.out.println ("Usage: java GetWebPage <URL>");
      System.exit (10);
    }

    if (!args[0].startsWith ("http://")) {
      System.out.println ("Please specify a legal http URL.");
      System.exit (10);
    }

    resource = args[0].substring (7);   // skip HTTP://

    slashPos = resource.indexOf('/');  // find host/file separator
    if (slashPos < 0) {
      resource = resource + "/index.html";
      slashPos = resource.indexOf ('/');
    }
    file = resource.substring (slashPos); // isolate host and file parts
    host = resource.substring (0,slashPos);

    System.out.println ("Host to contact: '" + host +"'");
    System.out.println ("File to fetch  : '" + file +"'");

    HTTP webConnection = new HTTP (host);
    if (webConnection != null) {
      BufferedReader in = webConnection.get (file);
      String line;
      while ((line = in.readLine()) != null) {  // read until EOF
        System.out.println( line );
      }
    }
    System.out.println ("\nDone.");
  }
}

//-------------------------------------------------------------------
class HTTP {

  public final static int HTTP_PORT = 80;

  InetAddress wwwHost;
  DataInputStream in;
  PrintStream out;

  public HTTP (String host) throws UnknownHostException {

    wwwHost = InetAddress.getByName (host);
    System.out.println ("WWW host = " + wwwHost);
 }

  public BufferedReader get (String file) throws IOException {
    Socket httpPipe;
    InputStream inn;
    OutputStream outt;
    BufferedReader ir;
    PrintWriter out;

    httpPipe = new Socket (wwwHost, HTTP_PORT);
    if (httpPipe == null) {
      return null;
    }

    // get raw streams
    inn  = httpPipe.getInputStream();
    outt = httpPipe.getOutputStream();

    // turn into useful ones
    ir   = new BufferedReader (new InputStreamReader (inn));
    out  = new PrintWriter (new OutputStreamWriter (outt), true);

    if (inn==null || outt==null || ir==null || out==null) {
      System.out.println ("Failed to open streams to socket.");
      return null;
    }

    // send GET request
    System.out.println ("GET " + file + " HTTP/1.0\n");
           out.println ("GET " + file + " HTTP/1.0\n");

      // read response until blank separator line
    String response;
    while ((response = ir.readLine()).length() > 0) {
      System.out.println (response);
    }

    return ir;  // return BufferedReader to let client read resource
  }
}
