01: import java.io.BufferedReader;
02: import java.io.InputStream;
03: import java.io.InputStreamReader;
04: import java.io.IOException;
05: import java.io.OutputStream;
06: import java.io.PrintWriter;
07: import java.net.Socket;
08: 
09: /**
10:    This program demonstrates how to use a socket to communicate
11:    with a web server. Supply the name of the host and the
12:    resource on the command-line, for example
13:    java WebGet java.sun.com index.html
14: */
15: public class WebGet
16: {
17:    public static void main(String[] args) throws IOException
18:    {
19:       // get command-line arguments
20: 
21:       if (args.length != 2)
22:       {
23:          System.out.println("usage: java WebGet host resource");
24:          System.exit(0);
25:       }
26:       String host = args[0];
27:       String resource = args[1];
28: 
29:       // open socket
30: 
31:       final int HTTP_PORT = 80;
32:       Socket s = new Socket(host, HTTP_PORT);
33: 
34:       // get streams
35:       
36:       InputStream in = s.getInputStream();
37:       OutputStream out = s.getOutputStream();
38: 
39:       // turn streams into readers and writers
40: 
41:       BufferedReader reader = new BufferedReader(
42:          new InputStreamReader(in));
43:       PrintWriter writer = new PrintWriter(out);      
44: 
45:       // send command
46: 
47:       String command = "GET /" + resource + " HTTP/1.0\n\n";
48:       writer.print(command);
49:       writer.flush();
50: 
51:       // read server response
52: 
53:       boolean done = false;
54:       while (!done)
55:       {
56:          String input = reader.readLine();
57:          if (input == null) done = true;
58:          else System.out.println(input);
59:       }
60: 
61:       // always close the socket at the end
62: 
63:       s.close();      
64:    }
65: }