URLConnection
来源:互联网 发布:方正静蕾简体mac 编辑:程序博客网 时间:2024/06/04 17:46
URLConnection
extends ObjectClass 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 ofURLConnection
are not reusable: you must use a different instance for each connection to a resource.
Timeouts
URLConnection
supports two timeouts: a connect timeout
and aread 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
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 theHttpURLConnection
andHttpsURLConnection
subclasses. - Jar
Refer to theJarURLConnection
subclass.
Registering Additional Protocols
UsesetURLStreamHandlerFactory(URLStreamHandlerFactory)
to register handlers for other protocol types.Summary
URLConnection
is already connected to the remote resource.URLConnection
allows receiving data.URLConnection
allows sending data.URLConnection
.URLConnection
instance pointing to the resource specified by the given URL.allowUserInteraction
.URLConnection
is connected to.URLConnection
is connected to.content-encoding
or null
if this field is not set.content-length
or -1
if this field is not set.content-type
or null
if type is unknown.0
if this timestamp is unknown.allowUserInteraction
.getRequestProperty(String)
instead.doInput
which specifies whether this connection allows to receive data.doOutput
which specifies whether this connection allows to send data.0
if this timestamp is unknown.URLConnection
instances to determine the MIME-type according to a file extension.key
or null
if there is no field with this name.pos
ornull
if the header has fewer than pos
fields.posn
or null
if there are fewer than posn
fields.InputStream
for reading data from the resource pointed by thisURLConnection
.last-modified
or0
if this value is not set.OutputStream
for writing data to thisURLConnection
.Permission
object representing all needed permissions to open this connection.0
if reads never timeout.null
if there is no field with this name.URLConnection
.URLConnection
allows to use caches.url
by resolving the filename extension with the internal FileNameMap.is
by reading its first few characters.allowUserInteraction
.allowUserInteraction
.setRequestProperty(String, String)
instead.URLConnection
allows input.URLConnection
allows output.URLConnection
instances to determine the MIME-type according to a filename extension.Fields
protected boolean allowUserInteraction
Unused by Android. This field can be accessed via getAllowUserInteraction()
andsetAllowUserInteraction(boolean)
.
protected boolean connected
Specifies whether this URLConnection
is already connected to the remote resource. If this field is set totrue
the flags for setting up the connection are not changeable anymore.
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
protected URLConnection(URL url)
Creates a new URLConnection
instance pointing to the resource specified by the given URL.
Parameters
URLConnection
will point to.Public Methods
public void addRequestProperty(String field,String newValue)
Adds the given property to the request header. Existing properties with the same name will not be overwritten by this method.
Parameters
Throws
null
.public abstract void connect()
Opens a connection to the resource. This method will not reconnect to a resource after the initial connection has been closed.
Throws
public boolean getAllowUserInteraction()
Returns allowUserInteraction
. Unused by Android.
public int getConnectTimeout()
Returns the connect timeout in milliseconds. (See {#setConnectTimeout}.)
public Object getContent ()
Returns an object representing the content of the resource this URLConnection
is 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
public Object getContent (Class[] types)
Returns an object representing the content of the resource this URLConnection
is 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 list types
.
Parameters
Returns
- the content representing object or
null
if the content type does not match with one of the specified types.
Throws
public String getContentEncoding ()
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()
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 ()
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()
Returns the timestamp when this response has been sent as a date in milliseconds since January 1, 1970 GMT or0
if this timestamp is unknown.
Returns
- the sending timestamp of the current response.
public static boolean getDefaultAllowUserInteraction()
Returns the default value of allowUserInteraction
. Unused by Android.
public static String getDefaultRequestProperty (String field)
This method was deprecated in API level 1.
Use getRequestProperty(String)
instead.
Returns null.
public boolean getDefaultUseCaches()
Returns the default setting whether this connection allows using caches.
Returns
- the value of the default setting
defaultUseCaches
.
See Also
useCaches
public boolean getDoInput()
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
doInput
public boolean getDoOutput()
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
doOutput
public long getExpiration()
Returns the timestamp when this response will be expired in milliseconds since January 1, 1970 GMT or0
if this timestamp is unknown.
Returns
- the value of the response header field
expires
.
public static FileNameMap getFileNameMap ()
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)
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 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
Returns
- the value of the header field.
public String getHeaderField (int pos)
Returns the header value at the field position pos
or null
if the header has fewer thanpos
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
Returns
- the value of the field at position
pos
.
public long getHeaderFieldDate(String field, long defaultValue)
Returns the specified header value as a date in milliseconds since January 1, 1970 GMT. Returns thedefaultValue
if no such header field could be found.
Parameters
Returns
- the value of the specified header field as a date in milliseconds.
public int getHeaderFieldInt(String field, int defaultValue)
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 anInteger
.
Parameters
Returns
- the value of the specified header field as a number.
public String getHeaderFieldKey (int posn)
Returns the name of the header field at the given position posn
ornull
if there are fewer than posn
fields. 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
Returns
- the header field name at the given position.
public Map<String, List<String>>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.
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
public InputStream getInputStream ()
Returns an InputStream
for 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
public long getLastModified()
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 ()
Returns an OutputStream
for writing data to this URLConnection
. It throws anUnknownServiceException
by default. This method must be overridden by its subclasses.
Returns
- the OutputStream to write data.
Throws
public Permission getPermission ()
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 benull
if 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
public int getReadTimeout()
Returns the read timeout in milliseconds, or 0
if reads never timeout.
public Map<String, List<String>>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.
public 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. The base implementation of this method returns alwaysnull
.
Parameters
Returns
- the value of the property.
Throws
public URL getURL ()
Returns the URL represented by this URLConnection
.
Returns
- the URL of this connection.
public boolean getUseCaches()
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)
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
Returns
- the guessed content type or
null
if the type could not be determined.
public static String guessContentTypeFromStream (InputStream is)
Determines the MIME-type of the resource represented by the input stream is
by reading its first few characters.
Parameters
Returns
- the guessed content type or
null
if the type could not be determined.
Throws
public void setAllowUserInteraction(boolean newValue)
Sets allowUserInteraction
. Unused by Android.
public void setConnectTimeout(int timeoutMillis)
Sets the maximum time in milliseconds to wait while connecting. Connecting to a server will fail with aSocketTimeoutException
if the timeout elapses before a connection is established. The default value of0
causes 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 inRFC 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
timeoutMillis < 0
.public static synchronized voidsetContentHandlerFactory (ContentHandlerFactory contentFactory)
Sets the internally used content handler factory. The content factory can only be set once during the lifetime of the application.
Parameters
Throws
public static void setDefaultAllowUserInteraction(boolean allows)
Sets the default value for allowUserInteraction
. Unused by Android.
public static void setDefaultRequestProperty(String field,String value)
This method was deprecated in API level 1.
Use setRequestProperty(String, String)
instead.
Does nothing.
public void setDefaultUseCaches(boolean newValue)
Sets the default value for the flag indicating whether this connection allows to use caches. ExistingURLConnection
s are unaffected.
Parameters
See Also
useCaches
public void setDoInput(boolean newValue)
Sets the flag indicating whether this URLConnection
allows input. It cannot be set after the connection is established.
Parameters
Throws
See Also
doInput
public void setDoOutput(boolean newValue)
Sets the flag indicating whether this URLConnection
allows output. It cannot be set after the connection is established.
Parameters
Throws
See Also
doOutput
public 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.
Parameters
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 to 0
.
Parameters
Throws
URLConnection
has already been connected.See Also
ifModifiedSince
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 aSocketTimeoutException
if the timeout elapses before data becomes available. The default value of0
disables read timeouts; read attempts will block indefinitely.
Parameters
public void setRequestProperty(String field,String newValue)
Sets the value of the specified request header field. The value will only be used by the currentURLConnection
instance. This method can only be called before the connection is established.
Parameters
Throws
field
is null
.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
Throws
See Also
useCaches
public String toString ()
Returns the string representation containing the name of this class and the URL.
Returns
- the string representation of this
URLConnection
instance.
- URLConnection
- URLConnection
- urlConnection
- URLConnection
- URLConnection
- URLConnection
- URLConnection
- URLConnection
- URLConnection
- URLConnection
- URLConnection
- UrlConnection
- URLConnection
- urlConnection
- URLConnection 详细
- HTTP URLConnection
- URLConnection简述!!!!
- URLConnection 详解
- iOS8需要兼容的内容
- Android推送方案
- android triple buffer
- Android 中Parcelable的作用
- android Wi-Fi集成之分析
- URLConnection
- Vim——打造Python IDE
- 关于多个布局文件中的view共用一个id的问题的探讨
- SVN打tag
- hibernate的HQL中in参数设置
- 关于EXP-00106: 数据库链接口令无效 问题处理
- java jsp多用户博客系统源代码下载
- php---预定义常量DIRECTORY_SEPARATOR
- TortoiseSvn :object of the same name is already scheduled for addition