to top
Android APIs
public abstract class

URLConnection

extends Object
java.lang.Object
   ↳ java.net.URLConnection
Known Direct Subclasses
Known Indirect Subclasses

Class Overview

A connection to a URL for reading or writing. For HTTP connections, see HttpURLConnection for documentation of HTTP-specific features.

For example, to retrieve ftp://mirror.csclub.uwaterloo.ca/index.html:

   URL url = new URL("ftp://mirror.csclub.uwaterloo.ca/index.html");
   URLConnection urlConnection = url.openConnection();
   InputStream in = new BufferedInputStream(urlConnection.getInputStream());
   try {
     readStream(in);
    finally {
     in.close();
   }
 }

URLConnection must be configured before it has connected to the remote resource. Instances of URLConnection are not reusable: you must use a different instance for each connection to a resource.

Timeouts

URLConnection supports two timeouts: a connect timeout and a read timeout. By default, operations never time out.

Built-in Protocols

  • File
    Resources from the local file system can be loaded using file: URIs. File connections can only be used for input.
  • FTP
    File Transfer Protocol (RFC 959) is supported, but with no public subclass. FTP connections can be used for input or output but not both.

    By default, FTP connections will be made using anonymous as the username and the empty string as the password. Specify alternate usernames and passwords in the URL: ftp://username:password@host/path.

  • HTTP and HTTPS
    Refer to the HttpURLConnection and HttpsURLConnection subclasses.
  • Jar
    Refer to the JarURLConnection subclass.

Registering Additional Protocols

Use setURLStreamHandlerFactory(URLStreamHandlerFactory) to register handlers for other protocol types.

Summary

Fields
protected boolean allowUserInteraction Specifies whether this URLConnection allows user interaction as it is needed for authentication purposes.
protected boolean connected Specifies whether this URLConnection is already connected to the remote resource.
protected boolean doInput Specifies whether this URLConnection allows receiving data.
protected boolean doOutput Specifies whether this URLConnection allows sending data.
protected long ifModifiedSince The data must be modified more recently than this time in milliseconds since January 1, 1970, GMT to be transmitted.
protected URL url The URL which represents the remote target of this URLConnection.
protected boolean useCaches Specifies whether the using of caches is enabled or the data has to be recent for every request.
Protected Constructors
URLConnection(URL url)
Creates a new URLConnection instance pointing to the resource specified by the given URL.
Public Methods
void addRequestProperty(String field, String newValue)
Adds the given property to the request header.
abstract void connect()
Opens a connection to the resource.
boolean getAllowUserInteraction()
Returns the option value which indicates whether user interaction is allowed on this URLConnection.
int getConnectTimeout()
Returns the connect timeout in milliseconds, or 0 if connect attempts never timeout.
Object getContent()
Returns an object representing the content of the resource this URLConnection is connected to.
Object getContent(Class[] types)
Returns an object representing the content of the resource this URLConnection is connected to.
String getContentEncoding()
Returns the content encoding type specified by the response header field content-encoding or null if this field is not set.
int getContentLength()
Returns the content length in bytes specified by the response header field content-length or -1 if this field is not set.
String getContentType()
Returns the MIME-type of the content specified by the response header field content-type or null if type is unknown.
long getDate()
Returns the timestamp when this response has been sent as a date in milliseconds since January 1, 1970 GMT or 0 if this timestamp is unknown.
static boolean getDefaultAllowUserInteraction()
Returns the default setting whether this connection allows user interaction.
static String getDefaultRequestProperty(String field)
This method is deprecated. Use getRequestProperty(String)
boolean getDefaultUseCaches()
Returns the default setting whether this connection allows using caches.
boolean getDoInput()
Returns the value of the option doInput which specifies whether this connection allows to receive data.
boolean getDoOutput()
Returns the value of the option doOutput which specifies whether this connection allows to send data.
long getExpiration()
Returns the timestamp when this response will be expired in milliseconds since January 1, 1970 GMT or 0 if this timestamp is unknown.
static FileNameMap getFileNameMap()
Returns the table which is used by all URLConnection instances to determine the MIME-type according to a file extension.
String getHeaderField(String key)
Returns the value of the header field specified by key or null if there is no field with this name.
String getHeaderField(int pos)
Returns the header value at the field position pos or null if the header has fewer than pos fields.
long getHeaderFieldDate(String field, long defaultValue)
Returns the specified header value as a date in milliseconds since January 1, 1970 GMT.
int getHeaderFieldInt(String field, int defaultValue)
Returns the specified header value as a number.
String getHeaderFieldKey(int posn)
Returns the name of the header field at the given position posn or null if there are fewer than posn fields.
Map<StringList<String>> getHeaderFields()
Returns an unmodifiable map of the response-header fields and values.
long getIfModifiedSince()
Returns the point of time since when the data must be modified to be transmitted.
InputStream getInputStream()
Returns an InputStream for reading data from the resource pointed by this URLConnection.
long getLastModified()
Returns the value of the response header field last-modified or 0 if this value is not set.
OutputStream getOutputStream()
Returns an OutputStream for writing data to this URLConnection.
Permission getPermission()
Returns a Permission object representing all needed permissions to open this connection.
int getReadTimeout()
Returns the read timeout in milliseconds, or 0 if reads never timeout.
Map<StringList<String>> getRequestProperties()
Returns an unmodifiable map of general request properties used by this connection.
String getRequestProperty(String field)
Returns the value of the request header property specified by {code field} or null if there is no field with this name.
URL getURL()
Returns the URL represented by this URLConnection.
boolean getUseCaches()
Returns the value of the flag which specifies whether this URLConnection allows to use caches.
static String guessContentTypeFromName(String url)
Determines the MIME-type of the given resource url by resolving the filename extension with the internal FileNameMap.
static String guessContentTypeFromStream(InputStream is)
Determines the MIME-type of the resource represented by the input stream is by reading its first few characters.
void setAllowUserInteraction(boolean newValue)
Sets the flag indicating whether this connection allows user interaction or not.
void setConnectTimeout(int timeoutMillis)
Sets the maximum time to wait for a connect to complete before giving up.
synchronized static void setContentHandlerFactory(ContentHandlerFactory contentFactory)
Sets the internally used content handler factory.
static void setDefaultAllowUserInteraction(boolean allows)
Sets the default value for the flag indicating whether this connection allows user interaction or not.
static void setDefaultRequestProperty(String field, String value)
This method is deprecated. Use setRequestProperty(String, String).
void setDefaultUseCaches(boolean newValue)
Sets the default value for the flag indicating whether this connection allows to use caches.
void setDoInput(boolean newValue)
Sets the flag indicating whether this URLConnection allows input.
void setDoOutput(boolean newValue)
Sets the flag indicating whether this URLConnection allows output.
static void setFileNameMap(FileNameMap map)
Sets the internal map which is used by all URLConnection instances to determine the MIME-type according to a filename extension.
void setIfModifiedSince(long newValue)
Sets the point of time since when the data must be modified to be transmitted.
void setReadTimeout(int timeoutMillis)
Sets the maximum time to wait for an input stream read to complete before giving up.
void setRequestProperty(String field, String newValue)
Sets the value of the specified request header field.
void setUseCaches(boolean newValue)
Sets the flag indicating whether this connection allows to use caches or not.
String toString()
Returns the string representation containing the name of this class and the URL.
[Expand]
Inherited Methods
From class java.lang.Object

Fields

protected boolean allowUserInteraction

Since: API Level 1

Specifies whether this URLConnection allows user interaction as it is needed for authentication purposes.

protected boolean connected

Since: API Level 1

Specifies whether this URLConnection is already connected to the remote resource. If this field is set to true the flags for setting up the connection are not changeable anymore.

protected boolean doInput

Since: API Level 1

Specifies whether this URLConnection allows receiving data.

protected boolean doOutput

Since: API Level 1

Specifies whether this URLConnection allows sending data.

protected long ifModifiedSince

Since: API Level 1

The data must be modified more recently than this time in milliseconds since January 1, 1970, GMT to be transmitted.

protected URL url

Since: API Level 1

The URL which represents the remote target of this URLConnection.

protected boolean useCaches

Since: API Level 1

Specifies whether the using of caches is enabled or the data has to be recent for every request.

Protected Constructors

protected URLConnection (URL url)

Since: API Level 1

Creates a new URLConnection instance pointing to the resource specified by the given URL.

Parameters
url the URL which represents the resource this URLConnection will point to.

Public Methods

public void addRequestProperty (String field, String newValue)

Since: API Level 1

Adds the given property to the request header. Existing properties with the same name will not be overwritten by this method.

Parameters
field the request property field name to add.
newValue the value of the property which is to add.
Throws
IllegalStateException if the connection has been already established.
NullPointerException if the property name is null.

public abstract void connect ()

Since: API Level 1

Opens a connection to the resource. This method will not reconnect to a resource after the initial connection has been closed.

Throws
IOException if an error occurs while connecting to the resource.

public boolean getAllowUserInteraction ()

Since: API Level 1

Returns the option value which indicates whether user interaction is allowed on this URLConnection.

Returns
  • the value of the option allowUserInteraction.

public int getConnectTimeout ()

Since: API Level 1

Returns the connect timeout in milliseconds, or 0 if connect attempts never timeout.

public Object getContent ()

Since: API Level 1

Returns an object representing the content of the resource this URLConnection is connected to. First, it attempts to get the content type from the method getContentType() which looks at the response header field "Content-Type". If none is found it will guess the content type from the filename extension. If that fails the stream itself will be used to guess the content type.

Returns
  • the content representing object.
Throws
IOException if an error occurs obtaining the content.

public Object getContent (Class[] types)

Since: API Level 1

Returns an object representing the content of the resource this URLConnection is connected to. First, it attempts to get the content type from the method getContentType() which looks at the response header field "Content-Type". If none is found it will guess the content type from the filename extension. If that fails the stream itself will be used to guess the content type. The content type must match with one of the list types.

Parameters
types the list of acceptable content types.
Returns
  • the content representing object or null if the content type does not match with one of the specified types.
Throws
IOException if an error occurs obtaining the content.

public String getContentEncoding ()

Since: API Level 1

Returns the content encoding type specified by the response header field content-encoding or null if this field is not set.

Returns
  • the value of the response header field content-encoding.

public int getContentLength ()

Since: API Level 1

Returns the content length in bytes specified by the response header field content-length or -1 if this field is not set.

Returns
  • the value of the response header field content-length.

public String getContentType ()

Since: API Level 1

Returns the MIME-type of the content specified by the response header field content-type or null if type is unknown.

Returns
  • the value of the response header field content-type.

public long getDate ()

Since: API Level 1

Returns the timestamp when this response has been sent as a date in milliseconds since January 1, 1970 GMT or 0 if this timestamp is unknown.

Returns
  • the sending timestamp of the current response.

public static boolean getDefaultAllowUserInteraction ()

Since: API Level 1

Returns the default setting whether this connection allows user interaction.

Returns
  • the value of the default setting defaultAllowUserInteraction.

public static String getDefaultRequestProperty (String field)

Since: API Level 1

This method is deprecated.
Use getRequestProperty(String)

Returns null.

public boolean getDefaultUseCaches ()

Since: API Level 1

Returns the default setting whether this connection allows using caches.

Returns
  • the value of the default setting defaultUseCaches.
See Also

public boolean getDoInput ()

Since: API Level 1

Returns the value of the option doInput which specifies whether this connection allows to receive data.

Returns
  • true if this connection allows input, false otherwise.
See Also

public boolean getDoOutput ()

Since: API Level 1

Returns the value of the option doOutput which specifies whether this connection allows to send data.

Returns
  • true if this connection allows output, false otherwise.
See Also

public long getExpiration ()

Since: API Level 1

Returns the timestamp when this response will be expired in milliseconds since January 1, 1970 GMT or 0 if this timestamp is unknown.

Returns
  • the value of the response header field expires.

public static FileNameMap getFileNameMap ()

Since: API Level 1

Returns the table which is used by all URLConnection instances to determine the MIME-type according to a file extension.

Returns
  • the file name map to determine the MIME-type.

public String getHeaderField (String key)

Since: API Level 1

Returns the value of the header field specified by key or null if there is no field with this name. The base implementation of this method returns always null.

Some implementations (notably HttpURLConnection) include a mapping for the null key; in HTTP's case, this maps to the HTTP status line and is treated as being at position 0 when indexing into the header fields.

Parameters
key the name of the header field.
Returns
  • the value of the header field.

public String getHeaderField (int pos)

Since: API Level 1

Returns the header value at the field position pos or null if the header has fewer than pos fields. The base implementation of this method returns always null.

Some implementations (notably HttpURLConnection) include a mapping for the null key; in HTTP's case, this maps to the HTTP status line and is treated as being at position 0 when indexing into the header fields.

Parameters
pos the field position of the response header.
Returns
  • the value of the field at position pos.

public long getHeaderFieldDate (String field, long defaultValue)

Since: API Level 1

Returns the specified header value as a date in milliseconds since January 1, 1970 GMT. Returns the defaultValue if no such header field could be found.

Parameters
field the header field name whose value is needed.
defaultValue the default value if no field has been found.
Returns
  • the value of the specified header field as a date in milliseconds.

public int getHeaderFieldInt (String field, int defaultValue)

Since: API Level 1

Returns the specified header value as a number. Returns the defaultValue if no such header field could be found or the value could not be parsed as an Integer.

Parameters
field the header field name whose value is needed.
defaultValue the default value if no field has been found.
Returns
  • the value of the specified header field as a number.

public String getHeaderFieldKey (int posn)

Since: API Level 1

Returns the name of the header field at the given position posn or null if there are fewer than posn fields. The base implementation of this method returns always null.

Some implementations (notably HttpURLConnection) include a mapping for the null key; in HTTP's case, this maps to the HTTP status line and is treated as being at position 0 when indexing into the header fields.

Parameters
posn the position of the header field which has to be returned.
Returns
  • the header field name at the given position.

public Map<StringList<String>> getHeaderFields ()

Since: API Level 1

Returns an unmodifiable map of the response-header fields and values. The response-header field names are the key values of the map. The map values are lists of header field values associated with a particular key name.

Some implementations (notably HttpURLConnection) include a mapping for the null key; in HTTP's case, this maps to the HTTP status line and is treated as being at position 0 when indexing into the header fields.

Returns
  • the response-header representing generic map.

public long getIfModifiedSince ()

Since: API Level 1

Returns the point of time since when the data must be modified to be transmitted. Some protocols transmit data only if it has been modified more recently than a particular time.

Returns
  • the time in milliseconds since January 1, 1970 GMT.
See Also

public InputStream getInputStream ()

Since: API Level 1

Returns an InputStream for reading data from the resource pointed by this URLConnection. It throws an UnknownServiceException by default. This method must be overridden by its subclasses.

Returns
  • the InputStream to read data from.
Throws
IOException if no InputStream could be created.

public long getLastModified ()

Since: API Level 1

Returns the value of the response header field last-modified or 0 if this value is not set.

Returns
  • the value of the last-modified header field.

public OutputStream getOutputStream ()

Since: API Level 1

Returns an OutputStream for writing data to this URLConnection. It throws an UnknownServiceException by default. This method must be overridden by its subclasses.

Returns
  • the OutputStream to write data.
Throws
IOException if no OutputStream could be created.

public Permission getPermission ()

Since: API Level 1

Returns a Permission object representing all needed permissions to open this connection. The returned permission object depends on the state of the connection and will be null if no permissions are necessary. By default, this method returns AllPermission. Subclasses should overwrite this method to return an appropriate permission object.

Returns
  • the permission object representing the needed permissions to open this connection.
Throws
IOException if an I/O error occurs while creating the permission object.

public int getReadTimeout ()

Since: API Level 1

Returns the read timeout in milliseconds, or 0 if reads never timeout.

public Map<StringList<String>> getRequestProperties ()

Since: API Level 1

Returns an unmodifiable map of general request properties used by this connection. The request property names are the key values of the map. The map values are lists of property values of the corresponding key name.

Returns
  • the request-property representing generic map.

public String getRequestProperty (String field)

Since: API Level 1

Returns the value of the request header property specified by {code field} or null if there is no field with this name. The base implementation of this method returns always null.

Parameters
field the name of the request header property.
Returns
  • the value of the property.
Throws
IllegalStateException if the connection has been already established.

public URL getURL ()

Since: API Level 1

Returns the URL represented by this URLConnection.

Returns
  • the URL of this connection.

public boolean getUseCaches ()

Since: API Level 1

Returns the value of the flag which specifies whether this URLConnection allows to use caches.

Returns
  • true if using caches is allowed, false otherwise.

public static String guessContentTypeFromName (String url)

Since: API Level 1

Determines the MIME-type of the given resource url by resolving the filename extension with the internal FileNameMap. Any fragment identifier is removed before processing.

Parameters
url the URL with the filename to get the MIME type.
Returns
  • the guessed content type or null if the type could not be determined.

public static String guessContentTypeFromStream (InputStream is)

Since: API Level 1

Determines the MIME-type of the resource represented by the input stream is by reading its first few characters.

Parameters
is the resource representing input stream to determine the content type.
Returns
  • the guessed content type or null if the type could not be determined.
Throws
IOException if an I/O error occurs while reading from the input stream.

public void setAllowUserInteraction (boolean newValue)

Since: API Level 1

Sets the flag indicating whether this connection allows user interaction or not. This method can only be called prior to the connection establishment.

Parameters
newValue the value of the flag to be set.
Throws
IllegalStateException if this method attempts to change the flag after the connection has been established.

public void setConnectTimeout (int timeoutMillis)

Since: API Level 1

Sets the maximum time to wait for a connect to complete before giving up. Connecting to a server will fail with a SocketTimeoutException if the timeout elapses before a connection is established. The default value of 0 disables connect timeouts; connect attempts may wait indefinitely.

Warning: if the hostname resolves to multiple IP addresses, this client will try each in RFC 3484 order. If connecting to each of these addresses fails, multiple timeouts will elapse before the connect attempt throws an exception. Host names that support both IPv6 and IPv4 always have at least 2 IP addresses.

Parameters
timeoutMillis the connect timeout in milliseconds. Non-negative.

public static synchronized void setContentHandlerFactory (ContentHandlerFactory contentFactory)

Since: API Level 1

Sets the internally used content handler factory. The content factory can only be set once during the lifetime of the application.

Parameters
contentFactory the content factory to be set.
Throws
Error if the factory has been already set.

public static void setDefaultAllowUserInteraction (boolean allows)

Since: API Level 1

Sets the default value for the flag indicating whether this connection allows user interaction or not. Existing URLConnections are unaffected.

Parameters
allows the default value of the flag to be used for new connections.

public static void setDefaultRequestProperty (String field, String value)

Since: API Level 1

This method is deprecated.
Use setRequestProperty(String, String).

Does nothing.

public void setDefaultUseCaches (boolean newValue)

Since: API Level 1

Sets the default value for the flag indicating whether this connection allows to use caches. Existing URLConnections are unaffected.

Parameters
newValue the default value of the flag to be used for new connections.
See Also

public void setDoInput (boolean newValue)

Since: API Level 1

Sets the flag indicating whether this URLConnection allows input. It cannot be set after the connection is established.

Parameters
newValue the new value for the flag to be set.
Throws
IllegalAccessError if this method attempts to change the value after the connection has been already established.
See Also

public void setDoOutput (boolean newValue)

Since: API Level 1

Sets the flag indicating whether this URLConnection allows output. It cannot be set after the connection is established.

Parameters
newValue the new value for the flag to be set.
Throws
IllegalAccessError if this method attempts to change the value after the connection has been already established.
See Also

public static void setFileNameMap (FileNameMap map)

Since: API Level 1

Sets the internal map which is used by all URLConnection instances to determine the MIME-type according to a filename extension.

Parameters
map the MIME table to be set.

public void setIfModifiedSince (long newValue)

Since: API Level 1

Sets the point of time since when the data must be modified to be transmitted. Some protocols transmit data only if it has been modified more recently than a particular time. The data will be transmitted regardless of its timestamp if this option is set to 0.

Parameters
newValue the time in milliseconds since January 1, 1970 GMT.
Throws
IllegalStateException if this URLConnection has already been connected.
See Also

public void setReadTimeout (int timeoutMillis)

Since: API Level 1

Sets the maximum time to wait for an input stream read to complete before giving up. Reading will fail with a SocketTimeoutException if the timeout elapses before data becomes available. The default value of 0 disables read timeouts; read attempts will block indefinitely.

Parameters
timeoutMillis the read timeout in milliseconds. Non-negative.

public void setRequestProperty (String field, String newValue)

Since: API Level 1

Sets the value of the specified request header field. The value will only be used by the current URLConnection instance. This method can only be called before the connection is established.

Parameters
field the request header field to be set.
newValue the new value of the specified property.
Throws
IllegalStateException if the connection has been already established.
NullPointerException if the parameter field is null.

public void setUseCaches (boolean newValue)

Since: API Level 1

Sets the flag indicating whether this connection allows to use caches or not. This method can only be called prior to the connection establishment.

Parameters
newValue the value of the flag to be set.
Throws
IllegalStateException if this method attempts to change the flag after the connection has been established.
See Also

public String toString ()

Since: API Level 1

Returns the string representation containing the name of this class and the URL.

Returns
  • the string representation of this URLConnection instance.