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.HttpURLConnection;
08: import java.net.URL;
09: import java.net.URLConnection;
10: 
11: /**
12:    This program demonstrates how to use an URL connection 
13:    to communicate with a web server. Supply the URL on the
14:    command-line, for example
15:     java UrlGet http://java.sun.com/index.html
16: */
17: public class URLGet
18: {
19:    public static void main(String[] args) throws IOException
20:    {
21:       // get command-line arguments
22: 
23:       if (args.length != 1)
24:       {
25:          System.out.println("usage: java UrlGet URL");
26:          System.exit(0);
27:       }
28: 
29:       // open connection
30: 
31:       URL u = new URL(args[0]);
32:       URLConnection connection = u.openConnection();
33: 
34:       // check if response code is HTTP_OK (200)
35:      
36:       HttpURLConnection httpConnection = (HttpURLConnection)connection;
37:       int code = httpConnection.getResponseCode();
38:       if (code != HttpURLConnection.HTTP_OK)
39:       {
40:          String message = httpConnection.getResponseMessage(); 
41:          System.out.println(code + " " + message);
42:          return;
43:       }
44: 
45:       // read server response
46: 
47:       InputStream in = connection.getInputStream();
48:       BufferedReader reader = new BufferedReader(
49:          new InputStreamReader(in));
50: 
51:       boolean done = false;
52:       while (!done)
53:       {
54:          String input = reader.readLine();
55:          if (input == null) done = true;
56:          else System.out.println(input);
57:       }
58:    }
59: }