Back Contents Next


  
  FAQ
  Java Tutorial
  Questions by Topic
  Sample test
  Other Certification sites
  Certification Tips
  Exam Objectives
  Java jobs
  Java News
  About Java Prepare
   Books
  Certification Books
  SCEA Books
  Online Books
   Tutorial Topics
  Language Fundamentals
  Operator and Assignments
  Declaration and Access Control
  Classes in Java
  AWT
  Event classes
  Threads
  Layout Managers
  Collections
  Files
   Advertisements
cover
   Feedback
  Please let us know your feedback
 
StoreBusters Marketing
javaprepare.com
your tool for Java Certification
home | tutorial | questions | test 1

5.4 URL Classes

The URL classes provide the implementation and support of connections to resources using a Uniform Resource Locator or URL. A URL is a pointer to a resource on the network. The resource might be a file or a more complicated entity such as a database. A URL consists of a protocol type, a host name, a port number, a file name, and an optional anchor or reference. A typical URL might be

 

http://www.madeupaddress.com:4567/index.html#page1

 

In this case the protocol is http, the host name is www.madeupaddress.com, the port number to which the TCP connection is made is 4567, the file name is "index.html" and the anchor is page1. If no port is specified, the default port for the specified protocol is used. The default HTTP port is 80, port 21 is reserved for FTP and port 23 is reserved for telnet. A relative URL contains a limited amount of information and relies on the information supplied by an absolute, or complete, URL to reach its destination.

 

The URL class hierarchy is shown in the figure below.

 

 

5.4.1 URL class30

public final class URL extends Object implements Serializable

 

Object

  URL

Interfaces

Serializable

 

A URL object represents a Uniform Resource Locator or URL.

URL() Constructor

Constructor

Syntax

URL()

public URL(String absoluteURL)
  throws MalformedURLException

 

public URL(URL contextURL, String url)
  throws MalformedURLException

 

public URL(URL contextURL, String url,
           URLStreamHandler handler)
  throws MalformedURLException

 

public URL(String protocol, String host, String file)
  throws MalformedURLException

 

public URL(String protocol, String host, int port,
           String file)
  throws MalformedURLException

 

public URL(String protocol, String host, int port,
           String file, URLStreamHandler handler)
  throws MalformedURLException

 

The first version creates a URL object using a String representation of an absolute URL.

 

The second version requires a URL object and a String representation of a URL. If the String does not represent an absolute URL, the URL object contextURL is used to fill in the missing pieces.

 

The third version is the same as the second except a URLStreamHandler object is specified to be the stream handler for the URL object.

 

The final three constructors create a URL object using separate arguments for the protocol, host, port number, filename, and stream handler. If the port and/or stream handler are not specified the default port and/or stream handler is used.

equals() Method

Method

Syntax

equals()

public boolean equals(Object obj)

 

equals() overrides the equals() method from the Object class and returns true if Object obj is a URL and contains the same URL as the invoking URL object.

hashCode() Method

Method

Syntax

hashCode()

public int hashCode()

 

hashCode() overrides the hashCode() method from the Object class and returns a hash code for the invoking URL object.

openConnection() Method

Method

Syntax

openConnection()

public URLConnection openConnection()
  throws IOException

 

openConnection() returns a URLConnection object that represents a connection to the remote object referred to by the invoking URL object.

openStream() Method

Method

Syntax

openStream()

public final InputStream openStream() throws IOException

 

openStream() opens a connection to the URL contained by the invoking URL object and returns an InputStream object for reading from that connection.

Methods to Return URL Properties

Method

Syntax

getAuthority()

public String getAuthority()

getContent()

public final Object getContent() throws IOException

 

public final Object getContent(Class[] classes)
  throws IOException

getFile()

public String getFile()

getHost()

public String getHost()

getPath()

public String getPath()

getPort()

public int getPort()

getProtocol()

public String getProtocol()

getQuery()

public int getQuery()

getRef()

public String getRef()

getUserInfo()

public String getUserInfo()

 

getAuthority() returns the authority portion of the invoking URL object.

 

getContent() returns the content of the invoking URL object as an Object appropriate for the type of content. The second version allows the method to specify which classes it is looking for.

 

getFile() returns the filename for the invoking URL object.

 

getHost() returns the host for the invoking URL object.

 

getPath() returns the path portion of the invoking URL object.

 

getPort() returns the port for the invoking URL object or 1 if the port is not set.

 

getProtocol() returns the protocol for the invoking URL object.

 

getQuery() returns the query portion of the invoking URL object.

 

getRef() returns the anchor for the invoking URL object.

 

getUserInfo() returns the user info portion of the invoking URL object.

sameFile() Method

Method

Syntax

sameFile()

public boolean sameFile(URL otherURL)

 

sameFile() returns true if the invoking URL object has the same protocol, host, port, and filename as the URL object otherURL.

toExternalForm() Method

Method

Syntax

toExternalForm()

public String toExternalForm()

 

toExternalForm() returns a String representation of the invoking URL object.

toString() Method

Method

Syntax

toString()

public String toString()

 

toString() overrides the toString() method from the Object class and returns a String representation of the invoking URL object.

 

Example: Using URL

 

This program uses a URL object to access the contents of an HTML file located on the Sun Java Website. Once the URL object is created, it can be used to open a connection to the Website. Information about the HTML file can be then accessed. The URL object can open up an InputStream and download the contents of the HTML file.

 

The machine on which this example is run will have to be connected to the Internet. It will not work if a proxy server must be used to connect to an external web site.

 

import java.net.*;

import java.io.*;

 

public class TestURL {

  int c;

 

  public TestURL() {

    try {

 

      // A URL object is created containing the URL of a Web page

      URL url =

        new URL("http://java.sun.com/products/jdk/1.3/docchanges.html");

 

      // A connection is made to the website

      URLConnection con = url.openConnection();

 

      // Information about the docchanges.html file can be accessed

      System.out.println("File name: " + url.getFile());

      System.out.println("Content type: " + con.getContentType());

      System.out.println("port: " + url.getPort());

      System.out.println("host: " + url.getHost());

      System.out.println("contents:");

 

      // An input stream is opened and the contents of the html page

      // are printed

      InputStream in = url.openStream();

 

      while ((c = in.read()) != -1) {

        System.out.print((char) c);

      }

      in.close();

 

    } catch (MalformedURLException me) {

      System.out.println("Error: " + me);

    } catch (IOException ioe) {

      System.out.println("Error: " + ioe);

    }

  }

 

  public static void main(String args[]) {

    TestURL tu = new TestURL();

  }

}

Output (may vary between runs)

File name: /products/jdk/1.3/docchanges.html

Content type: null

port: -1

host: java.sun.com

contents:

<html>

<head>

<title>Java(TM) 2 SDK Documentation Changes</title>

</head>

...

 

5.4.2 URLConnection Class

public abstract class URLConnection extends Object

 

Object

  URLConnection

 

The URLConnection class is the parent of all classes that represent a connection between an application and a URL and provides methods common to those sub- classes. Sub-classes of the URLConnection class support-protocol specific connections to a URL. A URLConnection sub-class object can be used to read from and write to the reference represented by the URL. URLConnection is an abstract class; a connection object is created by invoking the openConnection() method of a URL object.

connect() Method

Method

Syntax

connect()

public abstract void connect() throws IOException

 

connect() connects a URLConnection object to the resource specified by its URL object.

getContent() Method

Method

Syntax

getContent()

public Object getContent() throws IOException

 

public Object getContent(Class[] classes) throws IOException

 

getContent() returns the content of the resource specified by the URL object that is associated with the invoking URLConnection object. The return value is an object that encapsulates the content of the connection. If a Class array is specified, the subclass of Object returned will be the first match of the contents of the Class array.

getPermission() Method

Method

Syntax

getPermission()

public Permission getPermission() throws IOException

 

getPermission() returns a Permission object representing the permission necessary to make the connection, or null if no permission is required to make the connection.

getURL() Method

Method

Syntax

getURL()

public URL getURL()

 

getURL() returns the URL object that is associated with the invoking URLConnection object.

Request Property Methods

Method

Syntax

getDefaultRequestProperty()

public static String getDefaultRequestProperty (String key)

getRequestProperty()

public String getRequestProperty
       
(String key)

setDefaultRequestProperty()

public static void setDefaultRequestProperty
       
(String key, String value)

setRequestProperty()

public void setRequestProperty
        
(String key, String value)

 

These methods allow properties associated with the URLConnection request to be queried or modified. The request properties are protocol specific. For information on the request properties for an HTTP connection, consult

 

http://www.ietf.org/rfc/rfc2068.txt

 

getRequestProperty() returns the value associated with the given key.

 

setRequestProperty() specifies a key-value request property pair. Both the key and value are String objects.

 

getDefaultRequestProperty() returns the default request property value corresponding to the specified key. This method was deprecated as of Java 2.

 

setDefaultRequestProperty() sets the default key-value request property pair. This method was deprecated as of Java 2.

Resource Property Methods

Method

Syntax

getContentEncoding()

public String getContentEncoding()

getContentLength()

public int getContentLength()

getContentType()

public String getContentType()

getDate()

public long getDate()

getExpiration()

public long getExpiration()

getHeaderField()

public String getHeaderField
       
(int headerFieldIndex)

 

public String getHeaderField
       
(String headerFieldName)

getHeaderFieldDate()

public long getHeaderFieldDate
       
(String headerFieldName,
         long defaultTime)

getHeaderFieldInt()

public int getHeaderFieldInt
       
(String headerFieldName, int defaultInt)

getHeaderFieldKey()

public String getHeaderFieldKey
       
(int headerFieldIndex)

getLastModified()

public long getLastModified()

guessContentTypeFromStream()

public static String guessContentTypeFromStream
       
(InputStream is)
  throws IOException

 

These methods return information about various properties of the resource specified by the URL object that is associated with the invoking URLConnection object by accessing the header fields of the resource.

 

getContentEncoding() returns the content encoding of the resource.

 

getContentLength() returns the content length of the resource, or 1 if it the length is not known.

 

getContentType() returns the content type of the resource.

 

getDate() and getExpiration() return the sending date and expiration date of the resource. The return value is the time in milliseconds since Jan 1, 1970, or 0 if the dates are not known.

 

getHeaderField() returns the value of a header field. Either a header field index or header field name can be passed as an argument.

 

getHeaderFieldDate() returns the value of a header field parsed as a time value. The return value is the time in milliseconds since Jan 1, 1970. If the header field cannot be parsed as a time, the specified defaultTime value is returned.

 

getHeaderFieldInt() returns the value of a header field parsed as an int. If the header field cannot be parsed as an int, the specified defaultInt value is returned.

 

getHeaderFieldKey() returns the name of the header field at index headerFieldIndex.

 

getLastModified() returns the time in milliseconds since Jan 1, 1970 when the resource was last modified.

 

guessContentTypeFromStream() attempts to identify the type of input stream by examining the first few bytes at the beginning of the stream. This method is useful because sometimes HTTP servers return an incorrect content type.

Methods to Return Setup Parameters

Method

Syntax

getAllowUserInteraction()

public boolean getAllowUserInteraction()

getDefaultAllowUserInteraction()

public static boolean getDefaultAllowUserInteraction()

getDoInput()

public boolean getDoInput()

getDoOutput()

public boolean getDoOutput()

getIfModifiedSince()

public long getIfModifiedSince()

getDefaultUseCaches()

public boolean getDefaultUseCaches()

getUseCaches()

public boolean getUseCaches()

 

getAllowUserInteraction() returns true if the connection associated with the invoking URLConnection object allows user interaction.

 

getDefaultAllowUserInteraction() returns the default user interaction state.

 

getDoInput() returns true if the invoking URLConnection object is to be used for input.

 

getDoOutput() returns true if the invoking URLConnection object is to be used for output.

 

getIfModifiedSince() returns the ifModifiedSince time in milliseconds since Jan 1, 1970. This time is used to determine whether a resource should be downloaded or if a current copy of the resource exists at the local host.

 

getDefaultUseCaches() returns true if the use of caches is allowed by default.

 

getUseCaches() returns true if the invoking URLConnection object uses caches.

Methods to Change Setup Parameters

Method

Syntax

setAllowUserInteraction()

public void setAllowUserInteraction
       
(boolean interact)

setDefaultAllowUserInteraction()

public static void setDefaultAllowUserInteraction
       
(boolean interact)

setDoInput()

public void setDoInput(boolean input)

setDoOutput()

public void setDoOutput
       
(boolean output)

setIfModifiedSince()

public void setIfModifiedSince
       
(long time)

setDefaultUseCaches()

public void setDefaultUseCaches
       
(boolean useCachesByDefault)

setUseCaches()

public void setUseCaches
       
(boolean useCaches)

 

setAllowUserInteraction() specifies if the connection associated with the invoking URLConnection object allows user interaction.

 

setDefaultAllowUserInteraction() sets the default user interaction mode of the invoking URLConnection object.

 

setDoInput() is used to specify if the invoking URLConnection object will be used for input.

 

setDoOutput() is used to specify if the invoking URLConnection object will be used for output.

 

setIfModifiedSince() changes the ifModifiedSince time. This time, in milliseconds since Jan 1, 1970 is used to determine whether a resource should be downloaded or if a current copy of the resource exists at the local host.

 

setDefaultUseCaches() specifies if the use of caches is allowed by default.

 

setUseCaches() is used to specify if the invoking URLConnection object will use caches.

Stream Methods

Method

Syntax

getInputStream()

public InputStream getInputStream()
  throws IOException

getOutputStream()

public OutputStream getOutputStream()
  throws IOException

 

getInputStream() returns an InputStream object that can be used to read from the URL connection.

 

getOutputStream() returns an OutputStream object that can be used to write to the URL connection.

toString() Method

Method

Syntax

toString()

public String toString()

 

toString() returns a String representation of the invoking URLConnection object.

 

Example: Using URLConnection

 

See example Using URL on page 33 ,where a URLConnection object is created that represents a connection to an HTML file on a web site.

 

5.4.3 HttpURLConnection Class

public abstract class HttpURLConnection extends URLConnection

 

Object

  URLConnection

    HttpURLConnection

 

An HttpURLConnection object represents a connection to a resource specified by an HTTP URL and provides support for HTTP-specific features. The HttpURLConnection class provides HTTP response code constants and methods for parsing server responses. HttpURLConnection is an abstract class; a connection object is created by invoking the openConnection() method on a URL object.

HTTP Response Code Constants

Constant

public static final int HTTP_OK

public static final int HTTP_CREATED

public static final int HTTP_ACCEPTED

public static final int HTTP_NOT_AUTHORITATIVE

public static final int HTTP_NO_CONTENT

public static final int HTTP_RESET

public static final int HTTP_PARTIAL

public static final int HTTP_MULT_CHOICE

public static final int HTTP_MOVED_PERM

public static final int HTTP_MOVED_TEMP

public static final int HTTP_SEE_OTHER

public static final int HTTP_NOT_MODIFIED

public static final int HTTP_USE_PROXY

public static final int HTTP_BAD_REQUEST

public static final int HTTP_UNAUTHORIZED

public static final int HTTP_PAYMENT_REQUIRED

public static final int HTTP_FORBIDDEN

public static final int HTTP_NOT_FOUND

public static final int HTTP_BAD_METHOD

public static final int HTTP_NOT_ACCEPTABLE

public static final int HTTP_PROXY_AUTH

public static final int HTTP_CLIENT_TIMEOUT

public static final int HTTP_CONFLICT

public static final int HTTP_GONE

public static final int HTTP_LENGTH_REQUIRED

public static final int HTTP_PRECON_FAILED

public static final int HTTP_ENTITY_TOO_LARGE

public static final int HTTP_REQ_TOO_LONG

public static final int HTTP_UNSUPPORTED_TYPE

public static final int HTTP_VERSION

public static final int HTTP_INTERNAL_ERROR

public static final int HTTP_BAD_GATEWAY

public static final int HTTP_UNAVAILABLE

public static final int HTTP_GATEWAY_TIMEOUT

 

These constants represent response codes sent by the server in response to a request. See the Sun Java documentation for more details.

disconnect() Method

Method

Syntax

disconnect()

public abstract void disconnect()

 

disconnect() closes the connection to the server.

getErrorStream() Method

Method

Syntax

getErrorStream()

public InputStream getErrorStream()

 

getErrorStream() returns an InputStream object representing the error stream if the connection failed but some useful information was sent by the server. The information could then be read from the InputStream.

getResponseCode() Method

Method

Syntax

getResponseCode()

public int getResponseCode() throws IOException

 

getResponseCode() causes the server to return one of the HTTP response codes, or 1 if none can be found.

getResponseMessage() Method

Method

Syntax

getResponseMessage()

public String getResponseMessage()
  throws IOException

 

getResponseMessage() returns the message returned by the server along with the response status.

Redirects Methods

Method

Syntax

getFollowRedirects()

public static boolean getFollowRedirects()

setFollowRedirects()

public static void setFollowRedirects
       
(boolean redirects)

 

getFollowRedirects() returns true if the invoking HttpURLConnection object follows HTTP redirects. The default value is false.

 

setFollowRedirects() is used to change the redirects mode.

Request Method Methods

Method

Syntax

getRequestMethod()

public String getRequestMethod()

setRequestMethod()

public void setRequestMethod(String method)
  throws ProtocolException

 

getRequestMethod() returns the current HTTP request method for the URL request. The default method is "GET".

 

setRequestMethod() is used to change the method for the URL request. Valid arguments are "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", or "TRACE".

usingProxy() Method

Method

Syntax

usingProxy()

public abstract boolean usingProxy()

 

usingProxy() returns true if the URL connection is going through a proxy.

5.4.5 URLDecoder Class

public class URLDecoder extends Object

 

Object

  URLDecoder

 

The URLDecoder class is used to convert from a MIME format called x-www-form-urlencoded format. to a standard ASCII String object.

 

The x-www-form-urlencoded format is a subset of ASCII that can be read by a wide range of computer platforms. Its format is as follows: alphanumeric characters (a-z, A-Z, 0-9), the dash, the underscore, and the period are left unchanged. Spaces represented by the plus sign. All other characters are represented by the character '%' followed by a two digit hexadecimal number.

decode() Method

Method

Syntax

decode()

public static String decode(String str)

 

decode() returns a standard ASCII String object that is converted from the x-www-form-urlencoded String passed as an argument.

 

Example: Using URLDecoder

 

This example demonstrates the use of the URLDecoder class to decode a String from x-www-form-urlencoded form, and prints out the decoded form.

 

import java.net.*;

 

public class TestDecode {

  public static void main(String args[]) {

    String str = "Jackson%27s+bike-bell+cost+%245";

 

    try {

      String str2 = URLDecoder.decode(str);

      System.out.println(str2);

    } catch (Exception e) {}

  }

}

Output

Jackson's bike-bell cost $5

 

5.4.6 URLEncoder Class

public class URLEncoder extends Object

 

Object

  URLEncoder

 

The URLEncoder class is used to convert an ASCII String object into a MIME format called x-www-form-urlencoded format.

 

The x-www-form-urlencoded format is a subset of ASCII that can be read by a wide range of computer platforms. Its format is as follows: alphanumeric characters (a-z, A-Z, 0-9), the dash, the underscore, and the period are left unchanged. Spaces represented by the plus sign. All other characters are represented by the character '%' followed by a two digit hexadecimal number.

encode() Method

Method

Syntax

encode()

public static String encode(String str)

 

encode() returns a String object that is a x-www-form-urlencoded version of the String passed as an argument.

 

Example: Using URLEncoder

 

This example demonstrates the use of the URLEncoder class to encode a String into x-www-form-urlencoded form, and prints out the encoded form.

 

import java.net.*;

 

public class TestEncode {

  public static void main(String args[]) {

    String str = "Jackson's bike-bell cost $5";

 

    String str2 = URLEncoder.encode(str);

    System.out.println(str2);

  }

}

Output

Jackson%27s+bike-bell+cost+%245

 

 

 


BackContentsNext
©1999 Wrox Press Limited, US and UK.
home | tutorial | questions | test 1