1  import java.io.InputStream;
  2  import java.io.IOException;
  3  import java.io.OutputStream;
  4  import java.io.PrintWriter;
  5  import java.net.Socket;
  6  import java.util.Scanner;
  7  
  8  /**
  9     This program demonstrates how to use a socket to communicate
 10     with a web server. Supply the name of the host and the
 11     resource on the command-line, for example
 12     java WebGet horstmann.com index.html
 13  */
 14  public class WebGet
 15  {
 16     public static void main(String[] args) throws IOException
 17     {
 18        // Get command-line arguments
 19  
 20        String host;
 21        String resource;
 22  
 23        if (args.length == 2)
 24        {
 25           host = args[0];
 26           resource = args[1];
 27        }
 28        else
 29        {
 30           System.out.println("Getting / from horstmann.com");
 31           host = "horstmann.com";
 32           resource = "/";
 33        }
 34  
 35        // Open socket
 36  
 37        final int HTTP_PORT = 80;
 38        Socket s = new Socket(host, HTTP_PORT);
 39  
 40        // Get streams
 41        
 42        InputStream instream = s.getInputStream();
 43        OutputStream outstream = s.getOutputStream();
 44  
 45        // Turn streams into scanners and writers
 46  
 47        Scanner in = new Scanner(instream);
 48        PrintWriter out = new PrintWriter(outstream);      
 49  
 50        // Send command
 51  
 52        String command = "GET " + resource + " HTTP/1.1\n" 
 53           + "Host: " + host + "\n\n";
 54        out.print(command);
 55        out.flush();
 56  
 57        // Read server response
 58  
 59        while (in.hasNextLine())
 60        {
 61           String input = in.nextLine();
 62           System.out.println(input);
 63        }
 64  
 65        // Always close the socket at the end
 66  
 67        s.close();      
 68     }
 69  }