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 an 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           urlString = args[0];
 25        else
 26        {
 27           urlString = "http://horstmann.com/";
 28           System.out.println("Using " + urlString);
 29        }
 30  
 31        // Open connection
 32  
 33        URL u = new URL(urlString);
 34        URLConnection connection = u.openConnection();
 35  
 36        // Check if response code is HTTP_OK (200)
 37       
 38        HttpURLConnection httpConnection 
 39              = (HttpURLConnection) connection;
 40        int code = httpConnection.getResponseCode();
 41        String message = httpConnection.getResponseMessage(); 
 42        System.out.println(code + " " + message);
 43        if (code != HttpURLConnection.HTTP_OK)
 44           return;
 45  
 46        // Read server response
 47  
 48        InputStream instream = connection.getInputStream();
 49        Scanner in = new Scanner(instream);
 50  
 51        while (in.hasNextLine())
 52        {
 53           String input = in.nextLine();
 54           System.out.println(input);
 55        }
 56     }
 57  }