[Chapter 15] URLConnection

#

| Chapter 15 The java.net Package |

# URLConnection

## Name

URLConnection

## Synopsis

Class Name:

  `java.net.URLConnection`

Superclass:

  `java.lang.Object`

Immediate Subclasses:

  `java.net.HttpURLConnection`

Interfaces Implemented:

  None

Availability:

  JDK 1.0 or later

## Description

The `URLConnection` class is an `abstract` class that represents a connection to a `URL`. A subclass of `URLConnection` supports a protocol-specific connection. A `URLConnection` can both read from and write to a `URL`.

A `URLConnection` object is created when the `openConnection()` method is called for a `URL` object. At this point, the actual connection has not yet been made, so setup parameters and general request properties can be modified for the specific connection. The various `set` methods control the setup parameters and request properties. Then the actual connection is made by calling the `connect()` method. Finally, the remote object becomes available, and the header fields and the content are accessed using various `get` methods.

The `URLConnection` class defines quite a few methods for setting parameters and retrieving information. Fortunately, for simple connections, all of the setup parameters and request properties can be left alone, as they all have reasonable default values. In most cases, you'll only be interested in the `getInputStream()` and `getContent()` methods. `getInputStream()` provides an `InputStream` that reads from the `URL`, while `getContent()` uses a `ContentHandler` to return an `Object` that represents the content of the resource. These methods are mirrored by the `openStream()` and `getContent()` convenience methods in the `URL` class.

## Class Summary

    public abstract class java.net.URLConnection extends java.lang.Object {
      // Variables
      protected boolean allowUserInteraction;
      protected boolean connected;
      protected boolean doInput;
      protected boolean doOutput;
      public static FileNameMap fileNameMap;            // New in 1.1
      protected long ifModifiedSince;
      protected URL url;
      protected boolean useCaches;
      // Constructors
      protected URLConnection(URL url);
      // Class Methods
      public static boolean getDefaultAllowUserInteraction();
      public static String getDefaultRequestProperty(String key);
      protected static String guessContentTypeFromName(String fname);
      public static String guessContentTypeFromStream(InputStream is);
      public static synchronized void setContentHandlerFactory(
                                      ContentHandlerFactory fac);
      public static void setDefaultAllowUserInteraction(
                         boolean defaultallowuserinteraction);
      public static void setDefaultRequestProperty(String key,
                         String value);
      // Instance Methods
      public abstract void connect();
      public boolean getAllowUserInteraction();
      public Object getContent()
      public String getContentEncoding();
      public int getContentLength();
      public String getContentType();
      public long getDate();
      public boolean getDefaultUseCaches();
      public boolean getDoInput();
      public boolean getDoOutput();
      public long getExpiration();
      public String getHeaderField(int n);
      public String getHeaderField(String name);
      public long getHeaderFieldDate(String name, long default);
      public int getHeaderFieldInt(String name, int default);
      public String getHeaderFieldKey(int n);
      public long getIfModifiedSince();
      public InputStream getInputStream();
      public long getLastModified();
      public OutputStream getOutputStream();
      public String getRequestProperty(String key);
      public URL getURL();
      public boolean getUseCaches();
      public void setAllowUserInteraction(boolean allowuserinteraction);
      public void setDefaultUseCaches(boolean defaultusecaches);
      public void setDoInput(boolean doinput);
      public void setDoOutput(boolean dooutput);
      public void setIfModifiedSince(long ifmodifiedsince);
      public void setRequestProperty(String key, String value);
      public void setUseCaches(boolean usecaches);
      public String toString();
    }

## Variables

### allowUserInteraction

#### protected boolean allowUserInteraction

Description

  A flag that indicates whether or not user interaction is enabled for this connection. If this variable is `true`, it is possible to allow user interactions such as popping up dialog boxes. If it is `false`, no user interaction is allowed. The variable can be set by `setAllowUserInteraction()` and retrieved by `getAllowUserInteraction()`. The default value is `false`, unless the `setDefaultAllowUserInteraction()` method has been called, in which case that method call controls the default value.

### connected

#### protected boolean connected

Description

  A flag that indicates whether or not this object has established a connection to a remote host.

### doInput

#### protected boolean doInput

Description

  A flag that indicates whether or not this connection is enabled for input. Setting this variable to `true` indicates that the connection is going to read data. The variable can be set by `setDoInput()` and retrieved by `getDoInput()`. The default value is `true`.

### doOutput

#### protected boolean doOutput

Description

  A flag that indicates whether or not this connection is enabled for output. Setting this variable to `true` indicates that the connection is going to write data. The variable can be set by `setDoOutput()` and retrieved by `getDoOutput()`. The default value is `false`.

### fileNameMap

#### public static FileNameMap fileNameMap

Availability

  New as of JDK 1.1

Description

  A reference to the object that maps filename extensions to MIME type strings. This variable is used in `guessContentTypeFromName()`.

### ifModifiedSince

#### protected long ifModifiedSince

Description

  A time value, specified as the number of seconds since January 1, 1970, that controls whether or not a resource is fetched based on its last modification time. Some protocols do not bother to retrieve a resource if there is a current local cached copy. However, if the resource has been modified more recently than `ifModifiedSince`, it is retrieved. If `ifModifiedSince` is 0, the resource is always retrieved. The variable can be set by `setIfModifiedSince()` and retrieved by `getIfModifiedSince()`. The default value is 0, which means that the resource must always be retrieved.

### url

#### protected URL url

Description

  The resource to which this `URLConnection` connects. This variable is set to the value of the `URL` argument in the `URLConnection` constructor. It can be retrieved by `getURL()`.

### useCaches

#### protected boolean useCaches

Description

  A flag that indicates whether or not locally cached resources are used. Some protocols cache documents. If this variable is `true`, the protocol is allowed to use caching whenever possible. If it is `false`, the protocol must always try to retrieve the resource. The variable can be set by `setUseCaches()` and retrieved by `getUseCaches()`. The default value is `true`, unless the `setDefaultUseCaches()` method has been called, in which case that method call controls the default value.

## Constructors

### URLConnection

#### protected URLConnection(URL url)

Parameters

  `url`

    The `URL` to access.

Description

  This constructor creates a `URLConnection` object to manage a connection to the destination specified by the given `URL`. The actual connection is not created, however.

## Class Methods

### getDefaultAllowUserInteraction

#### public static boolean getDefaultAllowUserInteraction()

Returns

  `true` if user interaction is allowed by default; `false` otherwise.

Description

  This method returns the default value of the `allowUserInteraction` variable for all instances of `URLConnection`. The default value is `false`, unless the `setDefaultAllowUserInteraction()` method has been called, in which case that method call controls the default value.

### getDefaultRequestProperty

#### public static String getDefaultRequestProperty(String key)

Parameters

  `key`

    The name of a request property.

Returns

  The default value of the named request property.

Description

  This method returns the default value for the request property named by the `key` parameter.

### guessContentTypeFromName

#### protected static String guessContentTypeFromName(String fname)

Parameters

  `fname`

    A `String` that contains the name of a file.

Returns

  A guess at the MIME type of the given file, or `null` if a guess cannot be made.

Description

  This method uses the `FileNameMap` specified by the variable `fileNameMap` to return a MIME content type for the given filename.

### guessContentTypeFromStream

####

     protected static String guessContentTypeFromStream(InputStream is) throws IOException

Parameters

  `is`

    The input stream to inspect

Returns

  A guess at the MIME type of the given input stream, or `null` if a guess cannot be made.

Throws

  `IOException`

    If any kind of I/O error occurs.

Description

  This method looks at the first few bytes of an `InputStream` and returns a guess of the MIME content type. Note that the `InputStream` must support marks, which usually means that there is a `BufferedInputStream` at some level. Here are some strings that are recognized and the inferred content type:

String | MIME Type Guess
--- | ---
`#def` | `image/x-bitmap`
`<!` | `text/html`
`<body` | `text/html`
`<head>` | `text/html`
`<html>` | `text/html`
`! XPM2` | `image/x-pixmap`
`GIF8` | `image/gif`

### setContentHandlerFactory

####

     public static synchronized void setContentHandlerFactory(ContentHandlerFactory fac)

Parameters

  `fac`

    An object that implements `ContentHandlerFactory`.

Throws

  `Error`

    If the factory has already been defined.

  `SecurityException`

    If the application does not have permission to set the factory.

Description

  This method tells the `URLConnection` class to use the given `ContentHandlerFactory` object for all `URLConnection` objects. The purpose of this mechanism is to allow a program that hosts applets, such as a web browser, control over the creation of `ContentHandler` objects.

### setDefaultAllowUserInteraction

####

     public static void setDefaultAllowUserInteraction( boolean defaultallowuserinteraction)

Parameters

  `defaultallowuserinteraction`

    The new default value.

Description

  This method sets the default value of the `allowUserInteraction` variable for all new instances of `URLConnection`.

### setDefaultRequestProperty

####

     public static void setDefaultRequestProperty(String key, String value)

Parameters

  `key`

    The name of a request property.

  `value`

    The new default value.

Description

  This method sets the default value of the request property named by the `key` parameter.

## Instance Methods

### connect

#### public abstract void connect() throws IOException

Throws

  `IOException`

    If any kind of I/O error occurs.

Description

  When a `URLConnection` object is created, it is not immediately connected to the resource specified by its associated `URL` object. This method actually establishes the connection. If this method is called after the connection has been established, it does nothing.

  Before the connection is established, various parameters can be set with the `set` methods. After the connection has been established, it is an error to try to set these parameters.

  As they retrieve information about the resource specified by the `URL` object, many of the `get` methods require that the connection be established. If the connection has not been established when one of these methods is called, the connection is established implicitly.

### getAllowUserInteraction

#### public boolean getAllowUserInteraction()

Returns

  `true` if user interaction is allowed for this connection; `false` otherwise.

Description

  This method returns the value of the `allowUserInteraction` variable for this `URLConnection`.

### getContent

####

     public Object getContent() throws IOException, UnknownServiceException

Returns

  An `Object` created from this `URLConnection`.

Throws

  `IOException`

    If any kind of I/O error occurs.

  `UnknownServiceException`

    If the protocol cannot support the content type.

Description

  This method retrieves the content of the resource specified by the `URL` object associated with this `URLConnection`. If the connection for this object has not been established, the method implicitly establishes it.

  The method returns an object that encapsulates the content of the connection. For example, for a connection that has content type `image/jpeg`, the method might return a object that belongs to subclass of `Image,` or for content type `text/plain`, it might return a `String`. The `instanceof` operator should determine the specific type of object that is returned.

  The method first determines the content type of the connection by calling `getContentType()`. If this is the first time the content type has been seen, a content handler of type `ContentHandler` is created for the content type. Here are the steps that are taken to create a content handler:

  1. If an application has set up a `ContentHandlerFactory` by calling `setContentHandlerFactory()`, the method calls the `createContentHandler()` method of that object to create the content handler. The content type is passed as a `String` argument to that method.

  2. If no `ContentHandlerFactory` has been established, or the `createContentHandler()` method returns `null`, the method retrieves the value of the system property `java.content.handler.pkgs`. If this value is not `null`, it is interpreted as a list of packages separated by vertical bar (`|`) characters. The method then tries to load the class named package`.`contentType, where package is the name of the first package in the list and contentType is formed by taking the content-type string and replacing every slash (`/`) character with a period (`.`) and every other nonalphanumeric character with an underscore ( `_` ). If the class exists and is a subclass of `ContentHandler`, it is used as the `ContentHandler` for the content type. If the class does not exist, or if it exists but is not a subclass of `ContentHandler`, the method tries the next package in the list.

  3. If the previous step fails to find an appropriate content handler, the method tries to load the class named `sun.net.www.content.`contentType, where contentType is formed by taking the content-type string and replacing every slash (`/`) character with a period (`.`) and every other nonalphanumeric character with an underscore ( `_` ). If the class exists and is a subclass of `ContentHandler`, it is used as the `ContentHandler` for the content type. If the class does not exist, or if it exists but is not a subclass of `ContentHandler`, a `UnknownServiceException` is thrown.

### getContentEncoding

#### public String getContentEncoding()

Returns

  The content encoding, or `null` if it is not known.

Description

  This method retrieves the content encoding of the resource specified by the `URL` object associated with this `URLConnection`. In other words, the method returns the value of the `content-encoding` header field. If the connection for this object has not been established, the method implicitly establishes it.

### getContentLength

#### public int getContentLength()

Returns

  The content length or `-1` if it is not known.

Description

  This method retrieves the content length of the resource specified by the `URL` object associated with this `URLConnection`. In other words, the method returns the value of the `content-length` header field. If the connection for this object has not been established, the method implicitly establishes it.

### getContentType

#### public String getContentType()

Returns

  The content type, or `null` if it is not known.

Description

  This method retrieves the content type of the resource specified by the `URL` object associated with this `URLConnection`. In other words, the method returns the value of the `content-type` header field. This string is generally be a MIME type, such as `image/jpeg` or `text/html`. If the connection for this object has not been established, the method implicitly establishes it.

### getDate

#### public long getDate()

Returns

  The content date, or 0 if it is not known.

Description

  This method retrieves the date of the resource specified by the `URL` object associated with this `URLConnection`. In other words, the method returns the value of the `date` header field. The date is returned as the number of seconds since January 1, 1970. If the connection for this object has not been established, the method implicitly establishes it.

### getDefaultUseCaches

#### public boolean getDefaultUseCaches()

Returns

  `true` if the use of caches is allowed by default; `false` otherwise.

Description

  This method returns the default value of the `useCaches` variable for all instances of `URLConnection`. The default value is `true`, unless the `setDefaultUseCaches()` method has been called, in which case that method call controls the default value.

### getDoInput

#### public boolean getDoInput()

Returns

  `true` if this `URLConnection` is to be used for input; `false` otherwise.

Description

  This method returns the value of the `doInput` variable for this `URLConnection`.

### getDoOutput

#### public boolean getDoOutput()

Returns

  `true` if this `URLConnection` is to be used for output; `false` otherwise.

Description

  This method returns the value of the `doOutput` variable for this `URLConnection`.

### getExpiration

#### public long getExpiration()

Returns

  The content expiration date, or if it is not known.

Description

  This method retrieves the expiration date of the resource specified by the `URL` object associated with this `URLConnection`. In other words, the method returns the value of the `expires` header field. The date is returned as the number of seconds since January 1, 1970. If the connection for this object has not been established, the method implicitly establishes it.

### getHeaderField

#### public String getHeaderField(int n)

Parameters

  `n`

    A header field index.

Returns

  The value of the header field with the given index, or `null` if `n` is greater than the number of fields in the header.

Description

  This method retrieves the value of the header field at index `n` of the resource specified by the `URL` object associated with this `URLConnection`. If the connection for this object has not been established, the method implicitly establishes it.

#### public String getHeaderField(String name)

Parameters

  `name`

    A header field name.

Returns

  The value of the named header field, or `null` if the header field is not known or its value cannot be determined.

Description

  This method retrieves the value of the named header field of the resource specified by the `URL` object associated with this `URLConnection`. This method is a helper for methods like `getContentEncoding()` and `getContentType()`. If the connection for this object has not been established, the method implicitly establishes it.

### getHeaderFieldDate

#### public long getHeaderFieldDate(String name, long default)

Parameters

  `name`

    A header field name.

  `default`

    A default date value.

Returns

  The value of the named header field parsed as a date value, or `default` if the field is missing or cannot be parsed.

Description

  This method retrieves the value of the named header field of the resource specified by the `URL` object associated with this `URLConnection` and parses it as a date value. The date is returned as the number of seconds since January 1, 1970. If the value of the header field cannot be determined or it is not a properly formed date, the given default value is returned. If the connection for this object has not been established, the method implicitly establishes it.

### getHeaderFieldInt

#### public int getHeaderFieldInt(String name, int default)

Parameters

  `name`

    A header field name.

  `default`

    A default value.

Returns

  The value of the named header field parsed as a number, or `default` if the field is missing or cannot be parsed.

Description

  This method retrieves the value of the named header field of the resource specified by the `URL` object associated with this `URLConnection` and parses it as a number. If the value of the header field cannot be determined or it is not a properly formed integer, the given default value is returned. If the connection for this object has not been established, the method implicitly establishes it.

### getHeaderFieldKey

#### public String getHeaderFieldKey(int n)

Parameters

  `n`

    A header field index.

Returns

  The name of the header field at the given index, or `null` if `n` is greater than the number of fields in the header.

Description

  This method retrieves the name of the header field at index `n` of the resource specified by the `URL` object associated with this `URLConnection`. If the connection for this object has not been established, the method implicitly establishes it.

### getIfModifiedSince

#### public long getIfModifiedSince()

Returns

  The value of the `ifModifiedSince` variable.

Description

  This method returns the value of the `ifModifiedSince` variable for this `URLConnection`.

### getInputStream

####

     public InputStream getInputStream() throws IOException, UnknownServiceException

Returns

  An `InputStream` that reads data from this connection.

Throws

  `IOException`

    If any kind of I/O error occurs.

  `UnknownServiceException`

    If this protocol does not support input.

Description

  This method returns an `InputStream` that reads the contents of the resource specified by the `URL` object associated with this `URLConnection`.

### getLastModified

#### public long getLastModified()

Returns

  The content last-modified date, or if it is not known.

Description

  This method retrieves the last-modified date of the resource specified by the `URL` object associated with this `URLConnection`. In other words, the method returns the value of the `last-modified` header field. The date is returned as the number of seconds since January 1, 1970. If the connection for this object has not been established, the method implicitly establishes it.

### getOutputStream

####

     public OutputStream getOutputStream() throws IOException, UnknownServiceException

Returns

  An `OutputStream` that writes data to this connection.

Throws

  `IOException`

    If any kind of I/O error occurs.

  `UnknownServiceException`

    If this protocol does not support output.

Description

  This method returns an `OutputStream` that writes to the resource specified by the `URL` object associated with this `URLConnection`.

### getRequestProperty

#### public String getRequestProperty(String key)

Parameters

  `key`

    The name of a request property.

Returns

  The value of the named request property.

Description

  This method returns the value of the request property named by the `key` parameter.

### getURL

#### public URL getURL()

Returns

  The `URL` that this connection accesses.

Description

  This method returns a reference to the `URL` associated with this object. This is the value of the `url` variable for this `URLConnection`.

### getUseCaches

#### public boolean getUseCaches()

Returns

  `true` if this `URLConnection` uses caches; `false` otherwise.

Description

  This method returns the value of the `useCaches` variable for this `URLConnection`.

### setAllowUserInteraction

#### public void setAllowUserInteraction(boolean allowuserinteraction)

Parameters

  `allowuserinteraction`

    A `boolean` value that indicates whether user interaction is allowed or not.

Throws

  `IllegalAccessError`

    If this method is called after the connection has been established.

Description

  This method sets the value of the `allowUserInteraction` variable for this `URLConnection`. This method must be called before this object establishes a connection.

### setDefaultUseCaches

#### public void setDefaultUseCaches(boolean defaultusecaches)

Parameters

  `defaultusecaches`

    The new default value.

Description

  This method sets the default value of the `useCaches` variable for all new instances of `URLConnection`.

### setDoInput

#### public void setDoInput(boolean doinput)

Parameters

  `doinput`

    A `boolean` value that indicates if this connection is to be used for input.

Throws

  `IllegalAccessError`

    If this method is called after the connection has been established.

  Description

    This method sets the value of the `doInput` variable for this `URLConnection`. This method must be called before this object establishes a connection.

### setDoOutput

#### public void setDoOutput(boolean dooutput)

Parameters

  `dooutput`

    A `boolean` value that indicates if this connection is to be used for output.

Throws

  `IllegalAccessError`

    If this method is called after the connection has been established.

Description

  This method sets the value of the `doOutput` variable for this `URLConnection`. This method must be called before this object establishes a connection.

### setIfModifiedSince

#### public void setIfModifiedSince(long ifmodifiedsince)

Parameters

  `ifmodifiedsince`

    A time value, specified as the number of seconds since January 1, 1970.

Throws

  `IllegalAccessError`

    If this method is called after the connection has been established.

Description

  This method sets the value of the `ifModifiedSince` variable for this `URLConnection`. This method must be called before this object establishes a connection.

### setRequestProperty

#### public void setRequestProperty(String key, String value)

Parameters

  `key`

    The name of a request property.

  `value`

    The new value.

Throws

  `IllegalAccessError`

    If this method is called after the connection has been established.

Description

  This method sets the value of the request property named by the `key` parameter.

### setUseCaches

#### public void setUseCaches(boolean defaultusecaches)

Parameters

  `defaultusecaches`

    A `boolean` value that indicates if this connection uses caches.

Throws

  `IllegalAccessError`

    If this method is called after the connection has been established.

Description

  This method sets the value of the `useCaches` variable for this `URLConnection`. This method must be called before this object establishes a connection.

### toString

#### public String toString()

Returns

  A string representation of the `URLConnection`.

Overrides

  `Object.toString()`

Description

  This method returns a string representation of this `URLConnection`.

## Inherited Methods

Method | Inherited From | Method | Inherited From
--- | --- | --- | ---
`clone()` | `Object` | `equals(Object)` | `Object`
`finalize()` | `Object` | `getClass()` | `Object`
`hashCode()` | `Object` | `notify()` | `Object`
`notifyAll()` | `Object` | `wait()` | `Object`
`wait(long)` | `Object` | `wait(long, int)` | `Object`

## See Also

`ContentHandler`, `ContentHandlerFactory`, `Error`, `FileNameMap`, `HttpURLConnection`, `IllegalAccessError`, `InputStream`, `IOException`, `OutputStream`, `SecurityException`, `UnknownServiceException`, `URL`, `URLStreamHandler`, `URLStreamHandlerFactory`

URL |  | URLEncoder