The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. Instances of this class can be used both to read from and to write to the resource referenced by the URL. In general, creating a connection to a URL is a multistep process:

openConnection() connect()
Manipulate parameters that affect the connection to the remote resource. Interact with the resource; query header fields and contents.
---------------------------->
time
  1. The connection object is created by invoking the openConnection method on a URL.
  2. The setup parameters and general request properties are manipulated.
  3. The actual connection to the remote object is made, using the connect method.
  4. The remote object becomes available. The header fields and the contents of the remote object can be accessed.

The setup parameters are modified using the following methods:

and the general request properties are modified using the method:

Default values for the AllowUserInteraction and UseCaches parameters can be set using the methods setDefaultAllowUserInteraction and setDefaultUseCaches.

Each of the above set methods has a corresponding get method to retrieve the value of the parameter or general request property. The specific parameters and general request properties that are applicable are protocol specific.

The following methods are used to access the header fields and the contents after the connection is made to the remote object:

Certain header fields are accessed frequently. The methods:

provide convenient access to these fields. The getContentType method is used by the getContent method to determine the type of the remote object; subclasses may find it convenient to override the getContentType method.

In the common case, all of the pre-connection parameters and general request properties can be ignored: the pre-connection parameters and request properties default to sensible values. For most clients of this interface, there are only two interesting methods: getInputStream and getContent, which are mirrored in the URL class by convenience methods.

More information on the request properties and header fields of an http connection can be found at:

 http://www.ietf.org/rfc/rfc2068.txt
 
Note about fileNameMap: In versions prior to JDK 1.1.6, field fileNameMap of URLConnection was public. In JDK 1.1.6 and later, fileNameMap is private; accessor and mutator methods getFileNameMap and setFileNameMap are added to access it. This change is also described on the Compatibility page. Invoking the close() methods on the InputStream or OutputStream of an URLConnection after a request may free network resources associated with this instance, unless particular protocol specifications specify different behaviours for it.
Adds a general request property specified by a key-value pair. This method will not overwrite existing values associated with the same key.
Parameters
keythe keyword by which the request is known (e.g., "accept").
valuethe value associated with it.
Throws
IllegalStateExceptionif already connected
NullPointerExceptionif key is null
@since
1.4
Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

If the connect method is called when the connection has already been opened (indicated by the connected field having the value true), the call is ignored.

URLConnection objects go through two phases: first they are created, then they are connected. After being created, and before being connected, various options can be specified (e.g., doInput and UseCaches). After connecting, it is an error to try to set them. Operations that depend on being connected, like getContentLength, will implicitly perform the connection, if necessary.

Throws
SocketTimeoutExceptionif the timeout expires before the connection can be established
IOExceptionif an I/O error occurs while opening the connection.
Indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Parameters
objthe reference object with which to compare.
Return
true if this object is the same as the obj argument; false otherwise.
Returns the value of the allowUserInteraction field for this object.
Return
the value of the allowUserInteraction field for this object.
Returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
Return
The java.lang.Class object that represents the runtime class of the object. The result is of type {@code Class} where X is the erasure of the static type of the expression on which getClass is called.
Returns setting for connect timeout.

0 return implies that the option is disabled (i.e., timeout of infinity).

Return
an int that indicates the connect timeout value in milliseconds
@since
1.5
Retrieves the contents of this URL connection.

This method first determines the content type of the object by calling the getContentType method. If this is the first time that the application has seen that specific content type, a content handler for that content type is created:

  1. If the application has set up a content handler factory instance using the setContentHandlerFactory method, the createContentHandler method of that instance is called with the content type as an argument; the result is a content handler for that content type.
  2. If no content handler factory has yet been set up, or if the factory's createContentHandler method returns null, then the application loads the class named:
             sun.net.www.content.<contentType>
         
    where <contentType> is formed by taking the content-type string, replacing all slash characters with a period ('.'), and all other non-alphanumeric characters with the underscore character '_'. The alphanumeric characters are specifically the 26 uppercase ASCII letters 'A' through 'Z', the 26 lowercase ASCII letters 'a' through 'z', and the 10 ASCII digits '0' through '9'. If the specified class does not exist, or is not a subclass of ContentHandler, then an UnknownServiceException is thrown.
Return
the object fetched. The instanceof operator should be used to determine the specific kind of object returned.
Throws
IOExceptionif an I/O error occurs while getting the content.
UnknownServiceExceptionif the protocol does not support the content type.
Retrieves the contents of this URL connection.
Parameters
classesthe Class array indicating the requested types
Return
the object fetched that is the first match of the type specified in the classes array. null if none of the requested types are supported. The instanceof operator should be used to determine the specific kind of object returned.
Throws
IOExceptionif an I/O error occurs while getting the content.
UnknownServiceExceptionif the protocol does not support the content type.
Returns the value of the content-encoding header field.
Return
the content encoding of the resource that the URL references, or null if not known.
Returns the value of the content-length header field.
Return
the content length of the resource that this connection's URL references, or -1 if the content length is not known.
Returns the value of the content-type header field.
Return
the content type of the resource that the URL references, or null if not known.
Returns the value of the date header field.
Return
the sending date of the resource that the URL references, or 0 if not known. The value returned is the number of milliseconds since January 1, 1970 GMT.
Returns the default value of the allowUserInteraction field.

Ths default is "sticky", being a part of the static state of all URLConnections. This flag applies to the next, and all following URLConnections that are created.

Return
the default value of the allowUserInteraction field.
Returns the value of the default request property. Default request properties are set for every connection.
Parameters
keythe keyword by which the request is known (e.g., "accept").
Return
the value of the default request property for the specified key.
@deprecated
The instance specific getRequestProperty method should be used after an appropriate instance of URLConnection is obtained.
Returns the default value of a URLConnection's useCaches flag.

Ths default is "sticky", being a part of the static state of all URLConnections. This flag applies to the next, and all following URLConnections that are created.

Return
the default value of a URLConnection's useCaches flag.
Returns the value of this URLConnection's doInput flag.
Return
the value of this URLConnection's doInput flag.
Returns the value of this URLConnection's doOutput flag.
Return
the value of this URLConnection's doOutput flag.
Returns the value of the expires header field.
Return
the expiration date of the resource that this URL references, or 0 if not known. The value is the number of milliseconds since January 1, 1970 GMT.
Loads filename map (a mimetable) from a data file. It will first try to load the user-specific table, defined by "content.types.user.table" property. If that fails, it tries to load the default built-in table at lib/content-types.properties under java home.
Return
the FileNameMap
@since
1.2
Returns the value for the nth header field. It returns null if there are fewer than n+1fields.

This method can be used in conjunction with the getHeaderFieldKey method to iterate through all the headers in the message.

Parameters
nan index, where n>=0
Return
the value of the nth header field or null if there are fewer than n+1 fields
Returns the value of the named header field.

If called on a connection that sets the same header multiple times with possibly different values, only the last value is returned.

Parameters
namethe name of a header field.
Return
the value of the named header field, or null if there is no such field in the header.
Returns the value of the named field parsed as date. The result is the number of milliseconds since January 1, 1970 GMT represented by the named field.

This form of getHeaderField exists because some connection types (e.g., http-ng) have pre-parsed headers. Classes for that connection type can override this method and short-circuit the parsing.

Parameters
namethe name of the header field.
Defaulta default value.
Return
the value of the field, parsed as a date. The value of the Default argument is returned if the field is missing or malformed.
Returns the value of the named field parsed as a number.

This form of getHeaderField exists because some connection types (e.g., http-ng) have pre-parsed headers. Classes for that connection type can override this method and short-circuit the parsing.

Parameters
namethe name of the header field.
Defaultthe default value.
Return
the value of the named field, parsed as an integer. The Default value is returned if the field is missing or malformed.
Returns the key for the nth header field. It returns null if there are fewer than n+1 fields.
Parameters
nan index, where n>=0
Return
the key for the nth header field, or null if there are fewer than n+1 fields.
Returns an unmodifiable Map of the header fields. The Map keys are Strings that represent the response-header field names. Each Map value is an unmodifiable List of Strings that represents the corresponding field values.
Return
a Map of header fields
@since
1.4
Returns the value of this object's ifModifiedSince field.
Return
the value of this object's ifModifiedSince field.
Returns an input stream that reads from this open connection. A SocketTimeoutException can be thrown when reading from the returned input stream if the read timeout expires before data is available for read.
Return
an input stream that reads from this open connection.
Throws
IOExceptionif an I/O error occurs while creating the input stream.
UnknownServiceExceptionif the protocol does not support input.
Returns the value of the last-modified header field. The result is the number of milliseconds since January 1, 1970 GMT.
Return
the date the resource referenced by this URLConnection was last modified, or 0 if not known.
Returns an output stream that writes to this connection.
Return
an output stream that writes to this connection.
Throws
IOExceptionif an I/O error occurs while creating the output stream.
UnknownServiceExceptionif the protocol does not support output.
Returns a permission object representing the permission necessary to make the connection represented by this object. This method returns null if no permission is required to make the connection. By default, this method returns java.security.AllPermission. Subclasses should override this method and return the permission that best represents the permission required to make a a connection to the URL. For example, a URLConnection representing a file: URL would return a java.io.FilePermission object.

The permission returned may dependent upon the state of the connection. For example, the permission before connecting may be different from that after connecting. For example, an HTTP sever, say foo.com, may redirect the connection to a different host, say bar.com. Before connecting the permission returned by the connection will represent the permission needed to connect to foo.com, while the permission returned after connecting will be to bar.com.

Permissions are generally used for two purposes: to protect caches of objects obtained through URLConnections, and to check the right of a recipient to learn about a particular URL. In the first case, the permission should be obtained after the object has been obtained. For example, in an HTTP connection, this will represent the permission to connect to the host from which the data was ultimately fetched. In the second case, the permission should be obtained and tested before connecting.

Return
the permission object representing the permission necessary to make the connection represented by this URLConnection.
Throws
IOExceptionif the computation of the permission requires network or file I/O and an exception occurs while computing it.
Returns setting for read timeout. 0 return implies that the option is disabled (i.e., timeout of infinity).
Return
an int that indicates the read timeout value in milliseconds
@since
1.5
Returns an unmodifiable Map of general request properties for this connection. The Map keys are Strings that represent the request-header field names. Each Map value is a unmodifiable List of Strings that represents the corresponding field values.
Return
a Map of the general request properties for this connection.
Throws
IllegalStateExceptionif already connected
@since
1.4
Returns the value of the named general request property for this connection.
Parameters
keythe keyword by which the request is known (e.g., "accept").
Return
the value of the named general request property for this connection. If key is null, then null is returned.
Throws
IllegalStateExceptionif already connected
Returns the value of this URLConnection's URL field.
Return
the value of this URLConnection's URL field.
Returns the value of this URLConnection's useCaches field.
Return
the value of this URLConnection's useCaches field.
Tries to determine the content type of an object, based on the specified "file" component of a URL. This is a convenience method that can be used by subclasses that override the getContentType method.
Parameters
fnamea filename.
Return
a guess as to what the content type of the object is, based upon its file name.
Tries to determine the type of an input stream based on the characters at the beginning of the input stream. This method can be used by subclasses that override the getContentType method.

Ideally, this routine would not be needed. But many http servers return the incorrect content type; in addition, there are many nonstandard extensions. Direct inspection of the bytes to determine the content type is often more accurate than believing the content type claimed by the http server.

Parameters
isan input stream that supports marks.
Return
a guess at the content type, or null if none can be determined.
Throws
IOExceptionif an I/O error occurs while reading the input stream.
Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

Return
a hash code value for this object.
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.

The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
Set the value of the allowUserInteraction field of this URLConnection.
Parameters
allowuserinteractionthe new value.
Throws
IllegalStateExceptionif already connected
Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection. If the timeout expires before the connection can be established, a java.net.SocketTimeoutException is raised. A timeout of zero is interpreted as an infinite timeout.

Some non-standard implmentation of this method may ignore the specified timeout. To see the connect timeout set, please call getConnectTimeout().

Parameters
timeoutan int that specifies the connect timeout value in milliseconds
Throws
IllegalArgumentExceptionif the timeout parameter is negative
@since
1.5
Sets the ContentHandlerFactory of an application. It can be called at most once by an application.

The ContentHandlerFactory instance is used to construct a content handler from a content type

If there is a security manager, this method first calls the security manager's checkSetFactory method to ensure the operation is allowed. This could result in a SecurityException.

Parameters
facthe desired factory.
Throws
Errorif the factory has already been defined.
SecurityExceptionif a security manager exists and its checkSetFactory method doesn't allow the operation.
Sets the default value of the allowUserInteraction field for all future URLConnection objects to the specified value.
Parameters
defaultallowuserinteractionthe new value.
Sets the default value of a general request property. When a URLConnection is created, it is initialized with these properties.
Parameters
keythe keyword by which the request is known (e.g., "accept").
valuethe value associated with the key.
@deprecated
The instance specific setRequestProperty method should be used after an appropriate instance of URLConnection is obtained. Invoking this method will have no effect.
Sets the default value of the useCaches field to the specified value.
Parameters
defaultusecachesthe new value.
Sets the value of the doInput field for this URLConnection to the specified value.

A URL connection can be used for input and/or output. Set the DoInput flag to true if you intend to use the URL connection for input, false if not. The default is true.

Parameters
doinputthe new value.
Throws
IllegalStateExceptionif already connected
Sets the value of the doOutput field for this URLConnection to the specified value.

A URL connection can be used for input and/or output. Set the DoOutput flag to true if you intend to use the URL connection for output, false if not. The default is false.

Parameters
dooutputthe new value.
Throws
IllegalStateExceptionif already connected
Sets the FileNameMap.

If there is a security manager, this method first calls the security manager's checkSetFactory method to ensure the operation is allowed. This could result in a SecurityException.

Parameters
mapthe FileNameMap to be set
Throws
SecurityExceptionif a security manager exists and its checkSetFactory method doesn't allow the operation.
@since
1.2
Sets the value of the ifModifiedSince field of this URLConnection to the specified value.
Parameters
ifmodifiedsincethe new value.
Throws
IllegalStateExceptionif already connected
Sets the read timeout to a specified timeout, in milliseconds. A non-zero value specifies the timeout when reading from Input stream when a connection is established to a resource. If the timeout expires before there is data available for read, a java.net.SocketTimeoutException is raised. A timeout of zero is interpreted as an infinite timeout.

Some non-standard implementation of this method ignores the specified timeout. To see the read timeout set, please call getReadTimeout().

Parameters
timeoutan int that specifies the timeout value to be used in milliseconds
Throws
IllegalArgumentExceptionif the timeout parameter is negative
@since
1.5
Sets the general request property. If a property with the key already exists, overwrite its value with the new value.

NOTE: HTTP requires all request properties which can legally have multiple instances with the same key to use a comma-seperated list syntax which enables multiple properties to be appended into a single property.

Parameters
keythe keyword by which the request is known (e.g., "accept").
valuethe value associated with it.
Throws
IllegalStateExceptionif already connected
NullPointerExceptionif key is null
Sets the value of the useCaches field of this URLConnection to the specified value.

Some protocols do caching of documents. Occasionally, it is important to be able to "tunnel through" and ignore the caches (e.g., the "reload" button in a browser). If the UseCaches flag on a connection is true, the connection is allowed to use whatever caches it can. If false, caches are to be ignored. The default value comes from DefaultUseCaches, which defaults to true.

Parameters
usecachesa boolean indicating whether or not to allow caching
Throws
IllegalStateExceptionif already connected
Returns a String representation of this URL connection.
Return
a string representation of this URLConnection.
Causes current thread to wait until another thread invokes the method or the method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Throws
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until either another thread invokes the method or the method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor.

This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

  • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
  • Some other thread invokes the notifyAll method for this object.
  • Some other thread interrupts thread T.
  • The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.
The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object; once it has gained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout);
         ... // Perform action appropriate to condition
     }
 
(For more information on this topic, see Section 3.2.3 in Doug Lea's "Concurrent Programming in Java (Second Edition)" (Addison-Wesley, 2000), or Item 50 in Joshua Bloch's "Effective Java Programming Language Guide" (Addison-Wesley, 2001).

If the current thread is interrupted by another thread while it is waiting, then an InterruptedException is thrown. This exception is not thrown until the lock status of this object has been restored as described above.

Note that the wait method, as it places the current thread into the wait set for this object, unlocks only this object; any other objects on which the current thread may be synchronized remain locked while the thread waits.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Parameters
timeoutthe maximum time to wait in milliseconds.
Throws
IllegalArgumentExceptionif the value of timeout is negative.
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until another thread invokes the method or the method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

This method is similar to the wait method of one argument, but it allows finer control over the amount of time to wait for a notification before giving up. The amount of real time, measured in nanoseconds, is given by:

 1000000*timeout+nanos

In all other respects, this method does the same thing as the method of one argument. In particular, wait(0, 0) means the same thing as wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:

  • Another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.
  • The timeout period, specified by timeout milliseconds plus nanos nanoseconds arguments, has elapsed.

The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout, nanos);
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Parameters
timeoutthe maximum time to wait in milliseconds.
nanosadditional time, in nanoseconds range 0-999999.
Throws
IllegalArgumentExceptionif the value of timeout is negative or the value of nanos is not in the range 0-999999.
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.