01: import java.io.InputStream;
02: import java.io.IOException;
03: import java.io.OutputStream;
04: import java.io.PrintWriter;
05: import java.net.Socket;
06: import java.util.Scanner;
07: 
08: /**
09:    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 java.sun.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 java.sun.com");
31:          host = "java.sun.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.0\n\n";
53:       out.print(command);
54:       out.flush();
55: 
56:       // Read server response
57: 
58:       while (in.hasNextLine())
59:       {
60:          String input = in.nextLine();
61:          System.out.println(input);
62:       }
63: 
64:       // Always close the socket at the end
65: 
66:       s.close();      
67:    }
68: }