Using the URL Class (GetURL.java) : Utilities « Network Protocol « Java






Using the URL Class (GetURL.java)

     
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Chapter 2 Example
 * 
 * This program uses the standard Java URL class to open a connection to a web
 * page and download the contents.
 * 
 * @author Jeff Heaton
 * @version 1.0
 */
public class GetURL {

  /**
   * This method will display the URL specified by the parameter.
   * 
   * @param u
   *            The URL to display.
   */
  static protected void getURL(String u) {
    URL url;
    InputStream is;
    InputStreamReader isr;
    BufferedReader r;
    String str;

    try {
      System.out.println("Reading URL: " + u);
      url = new URL(u);
      is = url.openStream();
      isr = new InputStreamReader(is);
      r = new BufferedReader(isr);
      do {
        str = r.readLine();
        if (str != null)
          System.out.println(str);
      } while (str != null);
    } catch (MalformedURLException e) {
      System.out.println("Must enter a valid URL");
    } catch (IOException e) {
      System.out.println("Can not connect");
    }
  }

  /**
   * Program entry point.
   * 
   * @param args
   *            Command line arguments. Specified the URL to download.
   */
  static public void main(String args[]) {
    if (args.length < 1)
      System.out.println("Usage: GetURL ");
    else
      getURL(args[0]);
  }
}

           
         
    
    
    
    
  








Related examples in the same category

1.A class that encodes URL parameter values for MIDP devices.
2.Get the listing of everyone logged on
3.Scan your computer for ports in useScan your computer for ports in use
4.TCP socket monitor
5.Create Socket helper
6.Implements a TCP/IP bounce utility (proxy)
7.URL utilities class that makes it easy to create new URLs based off of old URLs without having to assemble or parse them yourself
8.Download from URL
9.URL ParserURL Parser
10.A simple class to load an URL in a browser
11.Using the java API URL class, extract the http/https hostname.
12.Utility class for URL decoding.
13.Utility class for URL encoding.
14.Allows easy downloading of files from HTTP sites
15.enum Http Status