next next up down toc Memos schedule allInOne PDF PDF mail
all, section 18.21.

18.21.  Connection to an URL

Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine. More information on the types of URLs and their formats can be found at: http://www.ncsa.uiuc.edu/demoweb/url-primer.html

Src/16/Url_Read.java.minusSTART_STOP


import java.io.*;
import java.net.URL;
import java.net.MalformedURLException;

public class Url_Read {

  public static void readFromUrl(String theUrl) {
  
  URL aUrl = null;
  BufferedReader in = null;
  String line;
  
  try {
          aUrl = new URL(theUrl);
          System.out.println("getPort() " + aUrl.getPort());
          System.out.println("getHost() " + aUrl.getHost());
          System.out.println("getProtocol() " + aUrl.getProtocol());
          System.out.println("getFile() " + aUrl.getFile());
          System.out.println("getRef() " + aUrl.getRef());

          in = new BufferedReader(
                   new InputStreamReader( aUrl.openStream() ) );

          while ( ( line = in.readLine() ) != null ) {
                System.out.println(line);
          }

          in.close();
          
  } catch (MalformedURLException e) {
          System.err.println("Something is wrong with this " +
                theUrl +  ".");
          System.exit(1);
  } catch (IOException e) {
          System.err.println("Couldn't get I/O for the connection to: "
                + theUrl );
          System.exit(1);
  }
  
  }

  public static void main( String args[] ) {

    if ( args.length != 1 )     {
        System.err.println(
             "Usage: java Url_Read url");
        System.exit(1);
    }

    try {
        readFromUrl(args[0]);
        
    }
    catch ( NumberFormatException e)    {
        System.out.println(args[0] + " is not a number ;-(");
    }

  }
}

Source Code: Src/16/Url_Read.java

% java Url_Read http://www.cs.rit.edu/~hpb | sed 15q
getPort() -1
getHost() www.cs.rit.edu
getProtocol() http
getFile() /~hpb
getRef() null
<HTML>

<HEAD>
<title>Hans-Peter Bischof's Home Page</title>
</HEAD>


<FRAMESET cols="230,*">
  <frame name="toc"    TARGET="_main" src="toc.html"     scrolling="auto">
  <frame name="intro"                 src="intro.html"   scrolling="auto">


back next up down toc Memos schedule allInOne pdf PDF mail

Created by unroff, java2html & & hp-tools. © by csfac. All Rights Reserved (2010).
It is not allowed to print these pages on a CAST printer.
Last modified: 01/April/10 (17:16)