/* HHTPClient              *
 * Esempio di Client HTTP  */

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

public class HTTPClient {
  public HTTPClient (String textURL) throws IOException {
    Socket socket = null;
    dissectURL (textURL);
    socket = connect ();
    try {
      getPage ();
    } finally {
      socket.close ();
    }
  }

  protected String host, file;
  protected int port;

  protected void dissectURL (String textURL) throws MalformedURLException {
    URL url = new URL (textURL);
    host = url.getHost ();
    port = url.getPort ();
    if (port == -1)
      port = 80;
    file = url.getFile ();
  }

  protected DataInputStream in;
  protected DataOutputStream out;

  protected Socket connect () throws IOException {
    System.err.println ("Connessione a " + host + ":" + port + "...");
    Socket socket = new Socket (host, port);
    System.err.println ("Connessione avvenuta.");

    BufferedOutputStream buffOut = new BufferedOutputStream (socket.getOutputStream ());
    out = new DataOutputStream (buffOut);
    in = new DataInputStream (socket.getInputStream ());

    return socket;
  }

  protected void getPage () throws IOException {
    System.err.println ("Richiesta del file " + file + " inviata...");
    out.writeBytes ("GET " + file + " HTTP/1.0\r\n\r\n");
    out.flush ();
    
    System.err.println ("Ricezione dati...");

    String input ;
    while ((input = in.readLine ()) != null)
        System.out.println (input);
  }

  public static void main (String args[]) throws IOException {
    if( args.length < 1 )
        throw new IOException( "Sintassi : HTTPClient URL" ) ;

    try {
        new HTTPClient (args[0]);
    } catch (IOException ex) {
        ex.printStackTrace ();        
    }

    System.out.println ("exit");
  }
}
