java.net

Class URLConnection

Known Direct Subclasses:
HttpURLConnection, JarURLConnection

public abstract class URLConnection
extends Object

This class models a connection that retrieves the information pointed to by a URL object. This is typically a connection to a remote node on the network, but could be a simple disk read.

A URLConnection object is normally created by calling the openConnection() method of a URL object. This method is somewhat misnamed because it does not actually open the connection. Instead, it return an unconnected instance of this object. The caller then has the opportunity to set various connection options prior to calling the actual connect() method.

After the connection has been opened, there are a number of methods in this class that access various attributes of the data, typically represented by headers sent in advance of the actual data itself.

Also of note are the getInputStream and getContent() methods which allow the caller to retrieve the actual data from the connection. Note that for some types of connections, writing is also allowed. The setDoOutput() method must be called prior to connecing in order to enable this, then the getOutputStream method called after the connection in order to obtain a stream to write the output to.

The getContent() method is of particular note. This method returns an Object that encapsulates the data returned. There is no way do determine the type of object that will be returned in advance. This is determined by the actual content handlers as described in the description of that method.

Field Summary

protected boolean
allowUserInteraction
This variable determines whether or not interaction is allowed with the user.
protected boolean
connected
Indicates whether or not a connection has been established to the destination specified in the URL
protected boolean
doInput
Indicates whether or not input can be read from this URL
protected boolean
doOutput
Indicates whether or not output can be sent to this URL
protected long
ifModifiedSince
If this value is non-zero, then the connection will only attempt to fetch the document pointed to by the URL if the document has been modified more recently than the date set in this variable.
protected URL
url
This is the URL associated with this connection
protected boolean
useCaches
If this flag is set, the protocol is allowed to cache data whenever it can (caching is not guaranteed).

Constructor Summary

URLConnection(URL url)
Creates a URL connection to a given URL.

Method Summary

void
addRequestProperty(String key, String value)
Adds a new request property by a key/value pair.
abstract void
connect()
Establishes the actual connection to the URL associated with this connection object
boolean
getAllowUserInteraction()
Returns a boolean flag indicating whether or not user interaction is allowed for this connection.
int
getConnectTimeout()
Returns the connection timeout speed, in milliseconds, or zero if the timeout is infinite or not set.
Object
getContent()
This method returns the content of the document pointed to by the URL as an Object.
Object
getContent(Class<T>[] classes)
Retrieves the content of this URLConnection
String
getContentEncoding()
Returns the value of the content-encoding field or null if it is not known or not present.
int
getContentLength()
Returns the value of the content-length header field or -1 if the value is not known or not present.
String
getContentType()
Returns the the content-type of the data pointed to by the URL.
long
getDate()
Returns the date of the document pointed to by the URL as reported in the date field of the header or 0 if the value is not present or not known.
static boolean
getDefaultAllowUserInteraction()
Returns the default flag for whether or not interaction with a user is allowed.
static String
getDefaultRequestProperty(String key)
Deprecated. 1.3 The method getRequestProperty should be used instead.
boolean
getDefaultUseCaches()
Returns the default value used to determine whether or not caching of documents will be done when possible.
boolean
getDoInput()
Returns the value of a flag indicating whether or not input is going to be done for this connection.
boolean
getDoOutput()
Returns a boolean flag indicating whether or not output will be done on this connection.
long
getExpiration()
Returns the value of the expires header or 0 if not known or present.
static FileNameMap
getFileNameMap()
This method returns the FileNameMap object being used to decode MIME types by file extension.
String
getHeaderField(int index)
Return a String representing the header value at the specified index.
String
getHeaderField(String name)
Returns a String representing the value of the header field having the named key.
long
getHeaderFieldDate(String name, long defaultValue)
Returns the value of the named header field as a date.
int
getHeaderFieldInt(String name, int defaultValue)
Returns the value of the named header field as an int.
String
getHeaderFieldKey(int index)
Returns a String representing the header key at the specified index.
Map>
getHeaderFields()
Returns an unmodifiable Map containing all sent header fields.
long
getIfModifiedSince()
Returns the ifModified since instance variable.
InputStream
getInputStream()
Returns an InputStream for this connection.
long
getLastModified()
Returns the value of the last-modified header field or 0 if not known known or not present.
OutputStream
getOutputStream()
Returns an OutputStream for this connection.
Permission
getPermission()
This method returns a Permission object representing the permissions required to access this URL.
int
getReadTimeout()
Returns the read timeout, in milliseconds, or zero if the timeout is infinite or not set.
Map>
getRequestProperties()
Returns an unmodifiable Map containing the request properties.
String
getRequestProperty(String key)
Returns the value of the named request property.
URL
getURL()
Returns the URL object associated with this connection
boolean
getUseCaches()
Returns a boolean flag indicating whether or not caching will be used (if possible) to store data downloaded via the connection.
static String
guessContentTypeFromName(String filename)
Returns the MIME type of a file based on the name of the file.
static String
guessContentTypeFromStream(InputStream is)
Returns the MIME type of a stream based on the first few characters at the beginning of the stream.
void
setAllowUserInteraction(boolean allow)
Sets a boolean flag indicating whether or not user interaction is allowed for this connection.
void
setConnectTimeout(int timeout)
Set the connection timeout speed, in milliseconds, or zero if the timeout is to be considered infinite.
static void
setContentHandlerFactory(ContentHandlerFactory factory)
Sets the ContentHandlerFactory for an application.
static void
setDefaultAllowUserInteraction(boolean allow)
Sets the default flag for whether or not interaction with a user is allowed.
static void
setDefaultRequestProperty(String key, String value)
Deprecated. 1.3 The method setRequestProperty should be used instead.
void
setDefaultUseCaches(boolean use)
Sets the default value used to determine whether or not caching of documents will be done when possible.
void
setDoInput(boolean input)
Sets the value of a flag indicating whether or not input is going to be done for this connection.
void
setDoOutput(boolean output)
Sets a boolean flag indicating whether or not output will be done on this connection.
static void
setFileNameMap(FileNameMap map)
This method sets the FileNameMap object being used to decode MIME types by file extension.
void
setIfModifiedSince(long ifmodifiedsince)
Sets the ifModified since instance variable.
void
setReadTimeout(int timeout)
Set the read timeout, in milliseconds, or zero if the timeout is to be considered infinite.
void
setRequestProperty(String key, String value)
Sets the value of the named request property.
void
setUseCaches(boolean usecaches)
Sets a boolean flag indicating whether or not caching will be used (if possible) to store data downloaded via the connection.
String
toString()
The methods prints the value of this object as a String by calling the toString() method of its associated URL.

Methods inherited from class java.lang.Object

clone, equals, extends Object> getClass, finalize, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Details

allowUserInteraction

protected boolean allowUserInteraction
This variable determines whether or not interaction is allowed with the user. For example, to prompt for a username and password.

connected

protected boolean connected
Indicates whether or not a connection has been established to the destination specified in the URL

doInput

protected boolean doInput
Indicates whether or not input can be read from this URL

doOutput

protected boolean doOutput
Indicates whether or not output can be sent to this URL

ifModifiedSince

protected long ifModifiedSince
If this value is non-zero, then the connection will only attempt to fetch the document pointed to by the URL if the document has been modified more recently than the date set in this variable. That date should be specified as the number of seconds since 1/1/1970 GMT.

url

protected URL url
This is the URL associated with this connection

useCaches

protected boolean useCaches
If this flag is set, the protocol is allowed to cache data whenever it can (caching is not guaranteed). If it is not set, the protocol must a get a fresh copy of the data.

This field is set by the setUseCaches method and returned by the getUseCaches method. Its default value is that determined by the last invocation of setDefaultUseCaches

Constructor Details

URLConnection

protected URLConnection(URL url)
Creates a URL connection to a given URL. A real connection is not made. Use connect() to do this.
Parameters:
url - The Object to create the URL connection to
See Also:
connect()

Method Details

addRequestProperty

public void addRequestProperty(String key,
                               String value)
Adds a new request property by a key/value pair. This method does not overwrite existing properties with the same key.
Parameters:
key - Key of the property to add
value - Value of the Property to add
Throws:
IllegalStateException - If already connected
NullPointerException - If key is null
Since:
1.4

connect

public abstract void connect()
            throws IOException
Establishes the actual connection to the URL associated with this connection object
Throws:
IOException - if an error occurs

getAllowUserInteraction

public boolean getAllowUserInteraction()
Returns a boolean flag indicating whether or not user interaction is allowed for this connection. (For example, in order to prompt for username and password info.
Returns:
true if user interaction is allowed, false otherwise

getConnectTimeout

public int getConnectTimeout()
Returns the connection timeout speed, in milliseconds, or zero if the timeout is infinite or not set.
Returns:
The timeout.
Since:
1.5

getContent

public Object getContent()
            throws IOException
This method returns the content of the document pointed to by the URL as an Object. The type of object depends on the MIME type of the object and particular content hander loaded. Most text type content handlers will return a subclass of InputStream. Images usually return a class that implements ImageProducer. There is not guarantee what type of object will be returned, however.

This class first determines the MIME type of the content, then creates a ContentHandler object to process the input. If the ContentHandlerFactory is set, then that object is called to load a content handler, otherwise a class called gnu.java.net.content.<content_type> is tried. If this handler does not exist, the method will simple return the InputStream returned by getInputStream(). Note that the default implementation of getInputStream() throws a UnknownServiceException so subclasses are encouraged to override this method.

Returns:
the content
Throws:
IOException - If an error with the connection occurs.

getContent

public Object getContent(Class<T>[] classes)
            throws IOException
Retrieves the content of this URLConnection
Parameters:
classes - The allowed classes for the content
Returns:
the content
Throws:
IOException - If an error occurs

getContentEncoding

public String getContentEncoding()
Returns the value of the content-encoding field or null if it is not known or not present.
Returns:
The content-encoding field

getContentLength

public int getContentLength()
Returns the value of the content-length header field or -1 if the value is not known or not present.
Returns:
The content-length field

getContentType

public String getContentType()
Returns the the content-type of the data pointed to by the URL. This method first tries looking for a content-type header. If that is not present, it attempts to use the file name to determine the content's MIME type. If that is unsuccessful, the method returns null. The caller may then still attempt to determine the MIME type by a call to guessContentTypeFromStream()
Returns:
The content MIME type

getDate

public long getDate()
Returns the date of the document pointed to by the URL as reported in the date field of the header or 0 if the value is not present or not known. If populated, the return value is number of seconds since midnight on 1/1/1970 GMT.
Returns:
The document date

getDefaultAllowUserInteraction

public static boolean getDefaultAllowUserInteraction()
Returns the default flag for whether or not interaction with a user is allowed. This will be used for all connections unless overridden
Returns:
true if user interaction is allowed, false otherwise

getDefaultRequestProperty

public static String getDefaultRequestProperty(String key)

Deprecated. 1.3 The method getRequestProperty should be used instead. This method does nothing now.

Returns the default value of a request property. This will be used for all connections unless the value of the property is manually overridden.
Parameters:
key - The request property to return the default value of
Returns:
The value of the default property or null if not available

getDefaultUseCaches

public boolean getDefaultUseCaches()
Returns the default value used to determine whether or not caching of documents will be done when possible.
Returns:
true if caches will be used, false otherwise

getDoInput

public boolean getDoInput()
Returns the value of a flag indicating whether or not input is going to be done for this connection. This default to true unless the doOutput flag is set to false, in which case this defaults to false.
Returns:
true if input is to be done, false otherwise

getDoOutput

public boolean getDoOutput()
Returns a boolean flag indicating whether or not output will be done on this connection. This defaults to false.
Returns:
true if output is to be done, false otherwise

getExpiration

public long getExpiration()
Returns the value of the expires header or 0 if not known or present. If populated, the return value is number of seconds since midnight on 1/1/1970 GMT.
Returns:
The expiration time.

getFileNameMap

public static FileNameMap getFileNameMap()
This method returns the FileNameMap object being used to decode MIME types by file extension.
Returns:
The FileNameMap.
Since:
1.2

getHeaderField

public String getHeaderField(int index)
Return a String representing the header value at the specified index. This allows the caller to walk the list of header fields. The analogous getHeaderField(int) method allows access to the corresponding key for this header field
Parameters:
index - The index into the header field list to retrieve the value for
Returns:
The header value or null if index is past the end of the headers

getHeaderField

public String getHeaderField(String name)
Returns a String representing the value of the header field having the named key. Returns null if the header field does not exist.
Parameters:
name - The key of the header field
Returns:
The value of the header field as a String

getHeaderFieldDate

public long getHeaderFieldDate(String name,
                               long defaultValue)
Returns the value of the named header field as a date. This date will be the number of seconds since midnight 1/1/1970 GMT or the default value if the field is not present or cannot be converted to a date.
Parameters:
name - The name of the header field
defaultValue - The default date if the header field is not found or can't be converted.
Returns:
The date value of the header filed or the default value if the field is missing or malformed

getHeaderFieldInt

public int getHeaderFieldInt(String name,
                             int defaultValue)
Returns the value of the named header field as an int. If the field is not present or cannot be parsed as an integer, the default value will be returned.
Parameters:
name - The header field key to lookup
defaultValue - The defaule value if the header field is not found or can't be parsed.
Returns:
The value of the header field or the default value if the field is missing or malformed

getHeaderFieldKey

public String getHeaderFieldKey(int index)
Returns a String representing the header key at the specified index. This allows the caller to walk the list of header fields. The analogous getHeaderField(int) method allows access to the corresponding value for this tag.
Parameters:
index - The index into the header field list to retrieve the key for.
Returns:
The header field key or null if index is past the end of the headers.

getHeaderFields

public Map> getHeaderFields()
Returns an unmodifiable Map containing all sent header fields.
Returns:
The map of header fields. The map consists of String keys with an unmodifiable List of String objects as value.
Since:
1.4

getIfModifiedSince

public long getIfModifiedSince()
Returns the ifModified since instance variable. If this value is non zero and the underlying protocol supports it, the actual document will not be fetched unless it has been modified since this time. The value returned will be 0 if this feature is disabled or the time expressed as the number of seconds since midnight 1/1/1970 GMT otherwise
Returns:
The ifModifiedSince value

getInputStream

public InputStream getInputStream()
            throws IOException
Returns an InputStream for this connection. As this default implementation returns null, subclasses should override this method
Returns:
An InputStream for this connection
Throws:
IOException - If an error occurs

getLastModified

public long getLastModified()
Returns the value of the last-modified header field or 0 if not known known or not present. If populated, the return value is the number of seconds since midnight on 1/1/1970.
Returns:
The last modified time

getOutputStream

public OutputStream getOutputStream()
            throws IOException
Returns an OutputStream for this connection. As this default implementation returns null, subclasses should override this method
Returns:
An OutputStream for this connection
Throws:
IOException - If an error occurs

getPermission

public Permission getPermission()
            throws IOException
This method returns a Permission object representing the permissions required to access this URL. This method returns java.security.AllPermission by default. Subclasses should override it to return a more specific permission. For example, an HTTP URL should return an instance of SocketPermission for the appropriate host and port.

Note that because of items such as HTTP redirects, the permission object returned might be different before and after connecting.

Returns:
A Permission object
Throws:
IOException - If the computation of the permission requires network or file I/O and an exception occurs while computing it

getReadTimeout

public int getReadTimeout()
Returns the read timeout, in milliseconds, or zero if the timeout is infinite or not set.
Returns:
The timeout.
Since:
1.5

getRequestProperties

public Map> getRequestProperties()
Returns an unmodifiable Map containing the request properties.
Returns:
The map of properties. The map consists of String keys with an unmodifiable List of String objects as value.
Throws:
IllegalStateException - If already connected
Since:
1.4

getRequestProperty

public String getRequestProperty(String key)
Returns the value of the named request property.
Parameters:
key - The name of the property
Returns:
Value of the property, or null if key is null.
Throws:
IllegalStateException - If already connected

getURL

public URL getURL()
Returns the URL object associated with this connection
Returns:
The URL for this connection.

getUseCaches

public boolean getUseCaches()
Returns a boolean flag indicating whether or not caching will be used (if possible) to store data downloaded via the connection.
Returns:
true if caching should be used if possible, false otherwise

guessContentTypeFromName

public static String guessContentTypeFromName(String filename)
Returns the MIME type of a file based on the name of the file. This works by searching for the file's extension in a list of file extensions and returning the MIME type associated with it. If no type is found, then a MIME type of "application/octet-stream" will be returned.
Parameters:
filename - The filename to determine the MIME type for
Returns:
The MIME type String

guessContentTypeFromStream

public static String guessContentTypeFromStream(InputStream is)
            throws IOException
Returns the MIME type of a stream based on the first few characters at the beginning of the stream. This routine can be used to determine the MIME type if a server is believed to be returning an incorrect MIME type. This method returns "application/octet-stream" if it cannot determine the MIME type.

NOTE: Overriding MIME types sent from the server can be obnoxious to user's. See Internet Exploder 4 if you don't believe me.

Parameters:
is - The InputStream to determine the MIME type from
Returns:
The MIME type
Throws:
IOException - If an error occurs

setAllowUserInteraction

public void setAllowUserInteraction(boolean allow)
Sets a boolean flag indicating whether or not user interaction is allowed for this connection. (For example, in order to prompt for username and password info.
Parameters:
allow - true if user interaction should be allowed, false otherwise.
Throws:
IllegalStateException - If already connected

setConnectTimeout

public void setConnectTimeout(int timeout)
            throws IllegalArgumentException
Set the connection timeout speed, in milliseconds, or zero if the timeout is to be considered infinite. Note that in certain socket implementations/platforms this method may not have any effect. Throws an IllegalArgumentException if timeout <320.
Parameters:
timeout - the timeout, in milliseconds.
Since:
1.5

setContentHandlerFactory

public static void setContentHandlerFactory(ContentHandlerFactory factory)
Sets the ContentHandlerFactory for an application. This can be called once and only once. If it is called again, then an Error is thrown. Unlike for other set factory methods, this one does not do a security check prior to setting the factory.
Parameters:
factory - The ContentHandlerFactory for this application
Throws:
SecurityException - If a security manager exists and its checkSetFactory method doesn't allow the operation

setDefaultAllowUserInteraction

public static void setDefaultAllowUserInteraction(boolean allow)
Sets the default flag for whether or not interaction with a user is allowed. This will be used for all connections unless overridden
Parameters:
allow - true to allow user interaction, false otherwise

setDefaultRequestProperty

public static void setDefaultRequestProperty(String key,
                                             String value)

Deprecated. 1.3 The method setRequestProperty should be used instead. This method does nothing now.

Sets the default value of a request property. This will be used for all connections unless the value of the property is manually overridden.
Parameters:
key - The request property name the default is being set for
value - The value to set the default to

setDefaultUseCaches

public void setDefaultUseCaches(boolean use)
Sets the default value used to determine whether or not caching of documents will be done when possible.
Parameters:
use - true to use caches if possible by default, false otherwise

setDoInput

public void setDoInput(boolean input)
Sets the value of a flag indicating whether or not input is going to be done for this connection. This default to true unless the doOutput flag is set to false, in which case this defaults to false.
Parameters:
input - true if input is to be done, false otherwise
Throws:
IllegalStateException - If already connected

setDoOutput

public void setDoOutput(boolean output)
Sets a boolean flag indicating whether or not output will be done on this connection. The default value is false, so this method can be used to override the default
Parameters:
output - ture if output is to be done, false otherwise
Throws:
IllegalStateException - If already connected

setFileNameMap

public static void setFileNameMap(FileNameMap map)
This method sets the FileNameMap object being used to decode MIME types by file extension.
Parameters:
map - The FileNameMap.
Throws:
SecurityException - If a security manager exists and its checkSetFactory method doesn't allow the operation
Since:
1.2

setIfModifiedSince

public void setIfModifiedSince(long ifmodifiedsince)
Sets the ifModified since instance variable. If this value is non zero and the underlying protocol supports it, the actual document will not be fetched unless it has been modified since this time. The value passed should be 0 if this feature is to be disabled or the time expressed as the number of seconds since midnight 1/1/1970 GMT otherwise.
Parameters:
ifmodifiedsince - The new value in milliseconds since January 1, 1970 GMT
Throws:
IllegalStateException - If already connected

setReadTimeout

public void setReadTimeout(int timeout)
            throws IllegalArgumentException
Set the read timeout, in milliseconds, or zero if the timeout is to be considered infinite. Note that in certain socket implementations/platforms this method may not have any effect. Throws an IllegalArgumentException if timeout <320.
Parameters:
timeout - - The timeout, in milliseconds.
Throws:
IllegalArgumentException - if timeout is negative.
Since:
1.5

setRequestProperty

public void setRequestProperty(String key,
                               String value)
Sets the value of the named request property. This method does overwrite the value of existing properties with the new value.
Parameters:
key - The name of the property
value - The value of the property
Throws:
IllegalStateException - If already connected
NullPointerException - If key is null
Since:
1.4
See Also:
URLConnection.getRequestProperty(String key), URLConnection.addRequestProperty(String key, String value)

setUseCaches

public void setUseCaches(boolean usecaches)
Sets a boolean flag indicating whether or not caching will be used (if possible) to store data downloaded via the connection.
Parameters:
usecaches - The new value
Throws:
IllegalStateException - If already connected

toString

public String toString()
The methods prints the value of this object as a String by calling the toString() method of its associated URL. Overrides Object.toString()
Overrides:
toString in interface Object
Returns:
A String representation of this object

URLConnection.java -- Abstract superclass for reading from URL's Copyright (C) 1998, 2002, 2003, 2004, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version.