Class URLConnection
- Direct Known Subclasses:
FileURLConnection,FtpURLConnection,HttpURLConnection,JarURLConnection
public abstract class URLConnection extends Object
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 usingfile: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
anonymousas 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 theHttpURLConnectionandHttpsURLConnectionsubclasses. - Jar
Refer to theJarURLConnectionsubclass.
Registering Additional Protocols
UseURL.setURLStreamHandlerFactory(java.net.URLStreamHandlerFactory) to register handlers for other
protocol types.-
Field Summary
Fields Modifier and Type Field Description protected booleanallowUserInteractionUnused by Android.protected booleanconnectedSpecifies whether thisURLConnectionis already connected to the remote resource.protected booleandoInputSpecifies whether thisURLConnectionallows receiving data.protected booleandoOutputSpecifies whether thisURLConnectionallows sending data.protected longifModifiedSinceThe data must be modified more recently than this time in milliseconds since January 1, 1970, GMT to be transmitted.protected URLurlThe URL which represents the remote target of thisURLConnection.protected booleanuseCachesSpecifies whether the using of caches is enabled or the data has to be recent for every request. -
Constructor Summary
Constructors Modifier Constructor Description protectedURLConnection(URL url)Creates a newURLConnectioninstance pointing to the resource specified by the given URL. -
Method Summary
Modifier and Type Method Description voidaddRequestProperty(String field, String newValue)Adds the given property to the request header.abstract voidconnect()Opens a connection to the resource.booleangetAllowUserInteraction()ReturnsallowUserInteraction.intgetConnectTimeout()Returns the connect timeout in milliseconds.ObjectgetContent()Returns an object representing the content of the resource thisURLConnectionis connected to.ObjectgetContent(Class[] types)Returns an object representing the content of the resource thisURLConnectionis connected to.StringgetContentEncoding()Returns the content encoding type specified by the response header fieldcontent-encodingornullif this field is not set.intgetContentLength()Returns the content length in bytes specified by the response header fieldcontent-lengthor-1if this field is not set.StringgetContentType()Returns the MIME-type of the content specified by the response header fieldcontent-typeornullif type is unknown.longgetDate()Returns the timestamp when this response has been sent as a date in milliseconds since January 1, 1970 GMT or0if this timestamp is unknown.static booleangetDefaultAllowUserInteraction()Returns the default value ofallowUserInteraction.static StringgetDefaultRequestProperty(String field)Deprecated.booleangetDefaultUseCaches()Returns the default setting whether this connection allows using caches.booleangetDoInput()Returns the value of the optiondoInputwhich specifies whether this connection allows to receive data.booleangetDoOutput()Returns the value of the optiondoOutputwhich specifies whether this connection allows to send data.longgetExpiration()Returns the timestamp when this response will be expired in milliseconds since January 1, 1970 GMT or0if this timestamp is unknown.static FileNameMapgetFileNameMap()Returns the table which is used by allURLConnectioninstances to determine the MIME-type according to a file extension.StringgetHeaderField(int pos)Returns the header value at the field positionposornullif the header has fewer thanposfields.StringgetHeaderField(String key)Returns the value of the header field specified bykeyornullif there is no field with this name.longgetHeaderFieldDate(String field, long defaultValue)Returns the specified header value as a date in milliseconds since January 1, 1970 GMT.intgetHeaderFieldInt(String field, int defaultValue)Returns the specified header value as a number.StringgetHeaderFieldKey(int posn)Returns the name of the header field at the given positionposnornullif there are fewer thanposnfields.Map<String,List<String>>getHeaderFields()Returns an unmodifiable map of the response-header fields and values.longgetIfModifiedSince()Returns the point of time since when the data must be modified to be transmitted.InputStreamgetInputStream()Returns anInputStreamfor reading data from the resource pointed by thisURLConnection.longgetLastModified()Returns the value of the response header fieldlast-modifiedor0if this value is not set.OutputStreamgetOutputStream()Returns anOutputStreamfor writing data to thisURLConnection.PermissiongetPermission()Returns aPermissionobject representing all needed permissions to open this connection.intgetReadTimeout()Returns the read timeout in milliseconds, or0if reads never timeout.Map<String,List<String>>getRequestProperties()Returns an unmodifiable map of general request properties used by this connection.StringgetRequestProperty(String field)Returns the value of the request header property specified by {code field} ornullif there is no field with this name.URLgetURL()Returns the URL represented by thisURLConnection.booleangetUseCaches()Returns the value of the flag which specifies whether thisURLConnectionallows to use caches.static StringguessContentTypeFromName(String url)Determines the MIME-type of the given resourceurlby resolving the filename extension with the internal FileNameMap.static StringguessContentTypeFromStream(InputStream is)Determines the MIME-type of the resource represented by the input streamisby reading its first few characters.voidsetAllowUserInteraction(boolean newValue)SetsallowUserInteraction.voidsetConnectTimeout(int timeoutMillis)Sets the maximum time in milliseconds to wait while connecting.static voidsetContentHandlerFactory(ContentHandlerFactory contentFactory)Sets the internally used content handler factory.static voidsetDefaultAllowUserInteraction(boolean allows)Sets the default value forallowUserInteraction.static voidsetDefaultRequestProperty(String field, String value)Deprecated.UsesetRequestProperty(String, String)instead.voidsetDefaultUseCaches(boolean newValue)Sets the default value for the flag indicating whether this connection allows to use caches.voidsetDoInput(boolean newValue)Sets the flag indicating whether thisURLConnectionallows input.voidsetDoOutput(boolean newValue)Sets the flag indicating whether thisURLConnectionallows output.static voidsetFileNameMap(FileNameMap map)Sets the internal map which is used by allURLConnectioninstances to determine the MIME-type according to a filename extension.voidsetIfModifiedSince(long newValue)Sets the point of time since when the data must be modified to be transmitted.voidsetReadTimeout(int timeoutMillis)Sets the maximum time to wait for an input stream read to complete before giving up.voidsetRequestProperty(String field, String newValue)Sets the value of the specified request header field.voidsetUseCaches(boolean newValue)Sets the flag indicating whether this connection allows to use caches or not.StringtoString()Returns the string representation containing the name of this class and the URL.
-
Field Details
-
url
The URL which represents the remote target of thisURLConnection. -
ifModifiedSince
protected long ifModifiedSinceThe data must be modified more recently than this time in milliseconds since January 1, 1970, GMT to be transmitted. -
useCaches
protected boolean useCachesSpecifies whether the using of caches is enabled or the data has to be recent for every request. -
connected
protected boolean connectedSpecifies whether thisURLConnectionis already connected to the remote resource. If this field is set totruethe flags for setting up the connection are not changeable anymore. -
doOutput
protected boolean doOutputSpecifies whether thisURLConnectionallows sending data. -
doInput
protected boolean doInputSpecifies whether thisURLConnectionallows receiving data. -
allowUserInteraction
protected boolean allowUserInteractionUnused by Android. This field can be accessed viagetAllowUserInteraction()andsetAllowUserInteraction(boolean).
-
-
Constructor Details
-
URLConnection
Creates a newURLConnectioninstance pointing to the resource specified by the given URL.- Parameters:
url- the URL which represents the resource thisURLConnectionwill point to.
-
-
Method Details
-
connect
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.
-
getAllowUserInteraction
public boolean getAllowUserInteraction()ReturnsallowUserInteraction. Unused by Android. -
getContent
Returns an object representing the content of the resource thisURLConnectionis connected to. First, it attempts to get the content type from the methodgetContentType()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.
-
getContent
Returns an object representing the content of the resource thisURLConnectionis connected to. First, it attempts to get the content type from the methodgetContentType()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 listtypes.- Parameters:
types- the list of acceptable content types.- Returns:
- the content representing object or
nullif the content type does not match with one of the specified types. - Throws:
IOException- if an error occurs obtaining the content.
-
getContentEncoding
Returns the content encoding type specified by the response header fieldcontent-encodingornullif this field is not set.- Returns:
- the value of the response header field
content-encoding.
-
getContentLength
public int getContentLength()Returns the content length in bytes specified by the response header fieldcontent-lengthor-1if this field is not set.- Returns:
- the value of the response header field
content-length.
-
getContentType
Returns the MIME-type of the content specified by the response header fieldcontent-typeornullif type is unknown.- Returns:
- the value of the response header field
content-type.
-
getDate
public long getDate()Returns the timestamp when this response has been sent as a date in milliseconds since January 1, 1970 GMT or0if this timestamp is unknown.- Returns:
- the sending timestamp of the current response.
-
getDefaultAllowUserInteraction
public static boolean getDefaultAllowUserInteraction()Returns the default value ofallowUserInteraction. Unused by Android. -
getDefaultRequestProperty
Deprecated.UsegetRequestProperty(java.lang.String)instead.Returns null. -
getDefaultUseCaches
public boolean getDefaultUseCaches()Returns the default setting whether this connection allows using caches.- Returns:
- the value of the default setting
defaultUseCaches. - See Also:
useCaches
-
getDoInput
public boolean getDoInput()Returns the value of the optiondoInputwhich specifies whether this connection allows to receive data.- Returns:
trueif this connection allows input,falseotherwise.- See Also:
doInput
-
getDoOutput
public boolean getDoOutput()Returns the value of the optiondoOutputwhich specifies whether this connection allows to send data.- Returns:
trueif this connection allows output,falseotherwise.- See Also:
doOutput
-
getExpiration
public long getExpiration()Returns the timestamp when this response will be expired in milliseconds since January 1, 1970 GMT or0if this timestamp is unknown.- Returns:
- the value of the response header field
expires.
-
getFileNameMap
Returns the table which is used by allURLConnectioninstances to determine the MIME-type according to a file extension.- Returns:
- the file name map to determine the MIME-type.
-
getHeaderField
Returns the header value at the field positionposornullif the header has fewer thanposfields. The base implementation of this method returns alwaysnull.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.
-
getHeaderFields
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.
- Since:
- 1.4
-
getRequestProperties
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.
- Since:
- 1.4
-
addRequestProperty
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 isnull.- Since:
- 1.4
-
getHeaderField
Returns the value of the header field specified bykeyornullif there is no field with this name. The base implementation of this method returns alwaysnull.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.
-
getHeaderFieldDate
Returns the specified header value as a date in milliseconds since January 1, 1970 GMT. Returns thedefaultValueif 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.
-
getHeaderFieldInt
Returns the specified header value as a number. Returns thedefaultValueif no such header field could be found or the value could not be parsed as anInteger.- 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.
-
getHeaderFieldKey
Returns the name of the header field at the given positionposnornullif there are fewer thanposnfields. The base implementation of this method returns alwaysnull.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.
-
getIfModifiedSince
public long getIfModifiedSince()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:
ifModifiedSince
-
getInputStream
Returns anInputStreamfor reading data from the resource pointed by thisURLConnection. 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.
-
getLastModified
public long getLastModified()Returns the value of the response header fieldlast-modifiedor0if this value is not set.- Returns:
- the value of the
last-modifiedheader field.
-
getOutputStream
Returns anOutputStreamfor writing data to thisURLConnection. It throws anUnknownServiceExceptionby default. This method must be overridden by its subclasses.- Returns:
- the OutputStream to write data.
- Throws:
IOException- if no OutputStream could be created.
-
getPermission
Returns aPermissionobject representing all needed permissions to open this connection. The returned permission object depends on the state of the connection and will benullif no permissions are necessary. By default, this method returnsAllPermission. 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.
-
getRequestProperty
Returns the value of the request header property specified by {code field} ornullif there is no field with this name. The base implementation of this method returns alwaysnull.- Parameters:
field- the name of the request header property.- Returns:
- the value of the property.
- Throws:
IllegalStateException- if the connection has been already established.
-
getURL
Returns the URL represented by thisURLConnection.- Returns:
- the URL of this connection.
-
getUseCaches
public boolean getUseCaches()Returns the value of the flag which specifies whether thisURLConnectionallows to use caches.- Returns:
trueif using caches is allowed,falseotherwise.
-
guessContentTypeFromName
Determines the MIME-type of the given resourceurlby 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
nullif the type could not be determined.
-
guessContentTypeFromStream
Determines the MIME-type of the resource represented by the input streamisby reading its first few characters.- Parameters:
is- the resource representing input stream to determine the content type.- Returns:
- the guessed content type or
nullif the type could not be determined. - Throws:
IOException- if an I/O error occurs while reading from the input stream.
-
setAllowUserInteraction
public void setAllowUserInteraction(boolean newValue)SetsallowUserInteraction. Unused by Android. -
setContentHandlerFactory
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.
-
setDefaultAllowUserInteraction
public static void setDefaultAllowUserInteraction(boolean allows)Sets the default value forallowUserInteraction. Unused by Android. -
setDefaultRequestProperty
Deprecated.UsesetRequestProperty(String, String)instead.Does nothing. -
setDefaultUseCaches
public void setDefaultUseCaches(boolean newValue)Sets the default value for the flag indicating whether this connection allows to use caches. ExistingURLConnections are unaffected.- Parameters:
newValue- the default value of the flag to be used for new connections.- See Also:
useCaches
-
setDoInput
public void setDoInput(boolean newValue)Sets the flag indicating whether thisURLConnectionallows 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:
doInput
-
setDoOutput
public void setDoOutput(boolean newValue)Sets the flag indicating whether thisURLConnectionallows 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:
doOutput
-
setFileNameMap
Sets the internal map which is used by allURLConnectioninstances to determine the MIME-type according to a filename extension.- Parameters:
map- the MIME table to be set.
-
setIfModifiedSince
public void setIfModifiedSince(long newValue)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 to0.- Parameters:
newValue- the time in milliseconds since January 1, 1970 GMT.- Throws:
IllegalStateException- if thisURLConnectionhas already been connected.- See Also:
ifModifiedSince
-
setRequestProperty
Sets the value of the specified request header field. The value will only be used by the currentURLConnectioninstance. 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 parameterfieldisnull.
-
setUseCaches
public void setUseCaches(boolean newValue)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:
useCaches
-
setConnectTimeout
public void setConnectTimeout(int timeoutMillis)Sets the maximum time in milliseconds to wait while connecting. Connecting to a server will fail with aSocketTimeoutExceptionif the timeout elapses before a connection is established. The default value of0causes us to do a blocking connect. This does not mean we will never time out, but it probably means you'll get a TCP timeout after several minutes.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.
- Throws:
IllegalArgumentException- iftimeoutMillis < 0.
-
getConnectTimeout
public int getConnectTimeout()Returns the connect timeout in milliseconds. (See {#setConnectTimeout}.) -
setReadTimeout
public void setReadTimeout(int timeoutMillis)Sets the maximum time to wait for an input stream read to complete before giving up. Reading will fail with aSocketTimeoutExceptionif the timeout elapses before data becomes available. The default value of0disables read timeouts; read attempts will block indefinitely.- Parameters:
timeoutMillis- the read timeout in milliseconds. Non-negative.
-
getReadTimeout
public int getReadTimeout()Returns the read timeout in milliseconds, or0if reads never timeout. -
toString
Returns the string representation containing the name of this class and the URL.
-
getRequestProperty(java.lang.String)instead.