1  import java.io.InputStream;
  2  import java.io.IOException;
  3  import java.io.OutputStream;
  4  import java.io.PrintWriter;
  5  import java.net.HttpURLConnection;
  6  import java.net.URL;
  7  import java.net.URLConnection;
  8  import java.util.Scanner;
  9  
 10  /**
 11     This program demonstrates how to use a URL connection 
 12     to communicate with a web server. Supply the URL on the
 13     command line, for example
 14        java URLGet http://horstmann.com/index.html
 15  */
 16  public class URLGet
 17  {
 18     public static void main(String[] args) throws IOException
 19     {
 20        // Get command line arguments
 21  
 22        String urlString;      
 23        if (args.length == 1)
 24        {
 25           urlString = args[0];
 26        }
 27        else
 28        {
 29           urlString = "http://horstmann.com/";
 30           System.out.println("Using " + urlString);
 31        }
 32  
 33        // Open connection
 34  
 35        URL u = new URL(urlString);
 36        URLConnection connection = u.openConnection();
 37  
 38        // Check if response code is HTTP_OK (200)
 39       
 40        HttpURLConnection httpConnection 
 41              = (HttpURLConnection) connection;
 42        int code = httpConnection.getResponseCode();
 43        String message = httpConnection.getResponseMessage(); 
 44        System.out.println(code + " " + message);
 45        if (code != HttpURLConnection.HTTP_OK)
 46        {
 47           return;
 48        }
 49  
 50        // Read server response
 51  
 52        InputStream instream = connection.getInputStream();
 53        Scanner in = new Scanner(instream);
 54  
 55        while (in.hasNextLine())
 56        {
 57           String input = in.nextLine();
 58           System.out.println(input);
 59        }
 60     }
 61  }