public
abstract
class
HttpURLConnection
extends URLConnection
| java.lang.Object | ||
| ↳ | java.net.URLConnection | |
| ↳ | java.net.HttpURLConnection | |
Known Direct Subclasses
|
An URLConnection for HTTP (RFC 2616) used to send and
receive data over the web. Data may be of any type and length. This class may
be used to send and receive streaming data whose length is not known in
advance.
Uses of this class follow a pattern:
HttpURLConnection by calling URL.openConnection() and casting the result to
HttpURLConnection.
setDoOutput(true) if they include a
request body. Transmit data by writing to the stream returned by getOutputStream().
getInputStream(). If the response has no body, that method returns an
empty stream.
HttpURLConnection should be closed by calling disconnect().
Disconnecting releases the resources held by a connection so they may
be closed or reused.
For example, to retrieve the webpage at http://www.android.com/:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
openConnection() on a URL with the "https"
scheme will return an HttpsURLConnection, which allows for
overriding the default HostnameVerifier and SSLSocketFactory. An application-supplied SSLSocketFactory
created from an SSLContext can
provide a custom X509TrustManager for verifying certificate chains and a custom
X509KeyManager for supplying
client certificates. See HttpsURLConnection for more details.
HttpURLConnection will follow up to five HTTP redirects. It will
follow redirects from one origin server to another. This implementation
doesn't follow redirects from HTTPS to HTTP or vice versa.
If the HTTP response indicates that an error occurred, getInputStream() will throw an IOException. Use getErrorStream() to read the error response. The headers can be read in
the normal way using getHeaderFields(),
setDoOutput(true).
For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance,
or setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in
memory before it is transmitted, wasting (and possibly exhausting) heap and
increasing latency.
For example, to perform an upload:
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
writeStream(out);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
BufferedInputStream or BufferedOutputStream. Callers that do only bulk
reads or writes may omit buffering.
When transferring large amounts of data to or from a server, use streams to limit how much data is in memory at once. Unless you need the entire body to be in memory at once, process it as a stream (rather than storing the complete body as a single byte array or string).
To reduce latency, this class may reuse the same underlying Socket
for multiple request/response pairs. As a result, HTTP connections may be
held open longer than necessary. Calls to disconnect() may return
the socket to a pool of connected sockets. This behavior can be disabled by
setting the http.keepAlive system property to false before
issuing any HTTP requests. The http.maxConnections property may be
used to control how many idle connections to each server will be held.
By default, this implementation of HttpURLConnection requests that
servers use gzip compression and it automatically decompresses the data for
callers of getInputStream(). The Content-Encoding and Content-Length
response headers are cleared in this case. Gzip compression can be disabled by
setting the acceptable encodings in the request header:
urlConnection.setRequestProperty("Accept-Encoding", "identity");
Setting the Accept-Encoding request header explicitly disables automatic decompression and leaves the response headers intact; callers must handle decompression as needed, according to the Content-Encoding header of the response.
getContentLength() returns the number of bytes transmitted and
cannot be used to predict how many bytes can be read from
getInputStream() for compressed streams. Instead, read that stream
until it is exhausted, i.e. when read() returns -1.
getURL() to test if your connection has been
unexpectedly redirected. This check is not valid until after
the response headers have been received, which you can trigger by calling
getHeaderFields() or getInputStream(). For example, to
check that a response was not redirected to an unexpected host:
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (!url.getHost().equals(urlConnection.getURL().getHost())) {
// we were redirected! Kick the user out to the browser to sign on?
...
} finally {
urlConnection.disconnect();
}
}
HttpURLConnection supports HTTP basic authentication. Use
Authenticator to set the VM-wide authentication handler:
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
});
}
Unless paired with HTTPS, this is not a secure mechanism for
user authentication. In particular, the username, password, request and
response are all transmitted over the network without encryption.
HttpURLConnection includes an extensible cookie manager.
Enable VM-wide cookie management using CookieHandler and CookieManager: CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
By default, CookieManager accepts cookies from the origin
server only. Two other policies are included: ACCEPT_ALL and ACCEPT_NONE. Implement
CookiePolicy to define a custom policy.
The default CookieManager keeps all accepted cookies in memory. It
will forget these cookies when the VM exits. Implement CookieStore to
define a custom cookie store.
In addition to the cookies set by HTTP responses, you may set cookies programmatically. To be included in HTTP request headers, cookies must have the domain and path properties set.
By default, new instances of HttpCookie work only with servers
that support RFC 2965
cookies. Many web servers support only the older specification, RFC 2109. For compatibility
with the most web servers, set the cookie version to 0.
For example, to receive www.twitter.com in French:
HttpCookie cookie = new HttpCookie("lang", "fr");
cookie.setDomain("twitter.com");
cookie.setPath("/");
cookie.setVersion(0);
cookieManager.getCookieStore().add(new URI("http://twitter.com/"), cookie);
HttpURLConnection uses the GET method by default. It will
use POST if setDoOutput(true) has been called.
Other HTTP methods (OPTIONS, HEAD, PUT, DELETE and TRACE) can be used with setRequestMethod(String).
HTTP or SOCKS proxy. To use a proxy, use URL.openConnection(Proxy) when creating the
connection.
This class includes transparent support for IPv6. For hosts with both IPv4 and IPv6 addresses, it will attempt to connect to each of a host's addresses until a connection is established.
android.net.http.HttpResponseCache for instructions on enabling HTTP
caching in your application.
close() on a readable InputStream could
poison the
connection pool. Work around this by disabling connection pooling:
private void disableConnectionReuseIfNecessary() {
// Work around pre-Froyo bugs in HTTP connection reuse.
if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}}
Each instance of HttpURLConnection may be used for one
request/response pair. Instances of this class are not thread safe.
Constants | |
|---|---|
int |
HTTP_ACCEPTED
Numeric status code, 202: Accepted |
int |
HTTP_BAD_GATEWAY
Numeric status code, 502: Bad Gateway |
int |
HTTP_BAD_METHOD
Numeric status code, 405: Bad Method |
int |
HTTP_BAD_REQUEST
Numeric status code, 400: Bad Request |
int |
HTTP_CLIENT_TIMEOUT
Numeric status code, 408: Client Timeout |
int |
HTTP_CONFLICT
Numeric status code, 409: Conflict |
int |
HTTP_CREATED
Numeric status code, 201: Created |
int |
HTTP_ENTITY_TOO_LARGE
Numeric status code, 413: Entity too large |
int |
HTTP_FORBIDDEN
Numeric status code, 403: Forbidden |
int |
HTTP_GATEWAY_TIMEOUT
Numeric status code, 504: Gateway timeout |
int |
HTTP_GONE
Numeric status code, 410: Gone |
int |
HTTP_INTERNAL_ERROR
Numeric status code, 500: Internal error |
int |
HTTP_LENGTH_REQUIRED
Numeric status code, 411: Length required |
int |
HTTP_MOVED_PERM
Numeric status code, 301 Moved permanently |
int |
HTTP_MOVED_TEMP
Numeric status code, 302: Moved temporarily |
int |
HTTP_MULT_CHOICE
Numeric status code, 300: Multiple choices |
int |
HTTP_NOT_ACCEPTABLE
Numeric status code, 406: Not acceptable |
int |
HTTP_NOT_AUTHORITATIVE
Numeric status code, 203: Not authoritative |
int |
HTTP_NOT_FOUND
Numeric status code, 404: Not found |
int |
HTTP_NOT_IMPLEMENTED
Numeric status code, 501: Not implemented |
int |
HTTP_NOT_MODIFIED
Numeric status code, 304: Not modified |
int |
HTTP_NO_CONTENT
Numeric status code, 204: No content |
int |
HTTP_OK
Numeric status code, 200: OK |
int |
HTTP_PARTIAL
Numeric status code, 206: Partial |
int |
HTTP_PAYMENT_REQUIRED
Numeric status code, 402: Payment required |
int |
HTTP_PRECON_FAILED
Numeric status code, 412: Precondition failed |
int |
HTTP_PROXY_AUTH
Numeric status code, 407: Proxy authentication required |
int |
HTTP_REQ_TOO_LONG
Numeric status code, 414: Request too long |
int |
HTTP_RESET
Numeric status code, 205: Reset |
int |
HTTP_SEE_OTHER
Numeric status code, 303: See other |
int |
HTTP_SERVER_ERROR
This constant was deprecated
in API level 1.
Use |
int |
HTTP_UNAUTHORIZED
Numeric status code, 401: Unauthorized |
int |
HTTP_UNAVAILABLE
Numeric status code, 503: Unavailable |
int |
HTTP_UNSUPPORTED_TYPE
Numeric status code, 415: Unsupported type |
int |
HTTP_USE_PROXY
Numeric status code, 305: Use proxy. |
int |
HTTP_VERSION
Numeric status code, 505: Version not supported |
Fields | |
|---|---|
protected
int |
chunkLength
If the HTTP chunked encoding is enabled this parameter defines the chunk-length. |
protected
int |
fixedContentLength
The byte count in the request body if it is both known and streamed; and -1 otherwise. |
protected
long |
fixedContentLengthLong
The byte count in the request body if it is both known and streamed; and -1 otherwise. |
protected
boolean |
instanceFollowRedirects
Flag to define whether the protocol will automatically follow redirects or not. |
protected
String |
method
The HTTP request method of this |
protected
int |
responseCode
The status code of the response obtained from the HTTP request. |
protected
String |
responseMessage
The HTTP response message which corresponds to the response code. |
Inherited fields |
|---|
From
class
java.net.URLConnection
|
Protected constructors | |
|---|---|
HttpURLConnection(URL url)
Constructs a new |
|
Public methods | |
|---|---|
abstract
void
|
disconnect()
Releases this connection so that its resources may be either reused or closed. |
String
|
getContentEncoding()
Returns the encoding used to transmit the response body over the network. |
InputStream
|
getErrorStream()
Returns an input stream from the server in the case of an error such as the requested file has not been found on the remote server. |
static
boolean
|
getFollowRedirects()
Returns the value of |
long
|
getHeaderFieldDate(String field, long defaultValue)
Returns the date value in milliseconds since |
boolean
|
getInstanceFollowRedirects()
Returns whether this connection follows redirects. |
Permission
|
getPermission()
Returns the permission object (in this case |
String
|
getRequestMethod()
Returns the request method which will be used to make the request to the remote HTTP server. |
int
|
getResponseCode()
Returns the response code returned by the remote HTTP server. |
String
|
getResponseMessage()
Returns the response message returned by the remote HTTP server. |
void
|
setChunkedStreamingMode(int chunkLength)
Stream a request body whose length is not known in advance. |
void
|
setFixedLengthStreamingMode(int contentLength)
Equivalent to |
void
|
setFixedLengthStreamingMode(long contentLength)
Configures this connection to stream the request body with the known
fixed byte count of |
static
void
|
setFollowRedirects(boolean auto)
Sets the flag of whether this connection will follow redirects returned by the remote server. |
void
|
setInstanceFollowRedirects(boolean followRedirects)
Sets whether this connection follows redirects. |
void
|
setRequestMethod(String method)
Sets the request command which will be sent to the remote HTTP server. |
abstract
boolean
|
usingProxy()
Returns whether this connection uses a proxy server or not. |
Inherited methods | |
|---|---|
From
class
java.net.URLConnection
| |
From
class
java.lang.Object
| |
int HTTP_ACCEPTED
Numeric status code, 202: Accepted
Constant Value: 202 (0x000000ca)
int HTTP_BAD_GATEWAY
Numeric status code, 502: Bad Gateway
Constant Value: 502 (0x000001f6)
int HTTP_BAD_METHOD
Numeric status code, 405: Bad Method
Constant Value: 405 (0x00000195)
int HTTP_BAD_REQUEST
Numeric status code, 400: Bad Request
Constant Value: 400 (0x00000190)
int HTTP_CLIENT_TIMEOUT
Numeric status code, 408: Client Timeout
Constant Value: 408 (0x00000198)
int HTTP_CONFLICT
Numeric status code, 409: Conflict
Constant Value: 409 (0x00000199)
int HTTP_CREATED
Numeric status code, 201: Created
Constant Value: 201 (0x000000c9)
int HTTP_ENTITY_TOO_LARGE
Numeric status code, 413: Entity too large
Constant Value: 413 (0x0000019d)
int HTTP_FORBIDDEN
Numeric status code, 403: Forbidden
Constant Value: 403 (0x00000193)
int HTTP_GATEWAY_TIMEOUT
Numeric status code, 504: Gateway timeout
Constant Value: 504 (0x000001f8)
int HTTP_GONE
Numeric status code, 410: Gone
Constant Value: 410 (0x0000019a)
int HTTP_INTERNAL_ERROR
Numeric status code, 500: Internal error
Constant Value: 500 (0x000001f4)
int HTTP_LENGTH_REQUIRED
Numeric status code, 411: Length required
Constant Value: 411 (0x0000019b)
int HTTP_MOVED_PERM
Numeric status code, 301 Moved permanently
Constant Value: 301 (0x0000012d)
int HTTP_MOVED_TEMP
Numeric status code, 302: Moved temporarily
Constant Value: 302 (0x0000012e)
int HTTP_MULT_CHOICE
Numeric status code, 300: Multiple choices
Constant Value: 300 (0x0000012c)
int HTTP_NOT_ACCEPTABLE
Numeric status code, 406: Not acceptable
Constant Value: 406 (0x00000196)
int HTTP_NOT_AUTHORITATIVE
Numeric status code, 203: Not authoritative
Constant Value: 203 (0x000000cb)
int HTTP_NOT_FOUND
Numeric status code, 404: Not found
Constant Value: 404 (0x00000194)
int HTTP_NOT_IMPLEMENTED
Numeric status code, 501: Not implemented
Constant Value: 501 (0x000001f5)
int HTTP_NOT_MODIFIED
Numeric status code, 304: Not modified
Constant Value: 304 (0x00000130)
int HTTP_NO_CONTENT
Numeric status code, 204: No content
Constant Value: 204 (0x000000cc)
int HTTP_OK
Numeric status code, 200: OK
Constant Value: 200 (0x000000c8)
int HTTP_PARTIAL
Numeric status code, 206: Partial
Constant Value: 206 (0x000000ce)
int HTTP_PAYMENT_REQUIRED
Numeric status code, 402: Payment required
Constant Value: 402 (0x00000192)
int HTTP_PRECON_FAILED
Numeric status code, 412: Precondition failed
Constant Value: 412 (0x0000019c)
int HTTP_PROXY_AUTH
Numeric status code, 407: Proxy authentication required
Constant Value: 407 (0x00000197)
int HTTP_REQ_TOO_LONG
Numeric status code, 414: Request too long
Constant Value: 414 (0x0000019e)
int HTTP_RESET
Numeric status code, 205: Reset
Constant Value: 205 (0x000000cd)
int HTTP_SEE_OTHER
Numeric status code, 303: See other
Constant Value: 303 (0x0000012f)
int HTTP_SERVER_ERROR
This constant was deprecated
in API level 1.
Use HTTP_INTERNAL_ERROR instead.
Numeric status code, 500: Internal error
Constant Value: 500 (0x000001f4)
int HTTP_UNAUTHORIZED
Numeric status code, 401: Unauthorized
Constant Value: 401 (0x00000191)
int HTTP_UNAVAILABLE
Numeric status code, 503: Unavailable
Constant Value: 503 (0x000001f7)
int HTTP_UNSUPPORTED_TYPE
Numeric status code, 415: Unsupported type
Constant Value: 415 (0x0000019f)
int HTTP_USE_PROXY
Numeric status code, 305: Use proxy.
Like Firefox and Chrome, this class doesn't honor this response code. Other implementations respond to this status code by retrying the request using the HTTP proxy named by the response's Location header field.
Constant Value: 305 (0x00000131)
int HTTP_VERSION
Numeric status code, 505: Version not supported
Constant Value: 505 (0x000001f9)
int chunkLength
If the HTTP chunked encoding is enabled this parameter defines the
chunk-length. Default value is -1 that means the chunked encoding
mode is disabled.
int fixedContentLength
The byte count in the request body if it is both known and streamed; and
-1 otherwise. If the byte count exceeds MAX_VALUE (2 GiB)
then the value of this field will be MAX_VALUE. In that
case use fixedContentLengthLong to access the exact byte count.
long fixedContentLengthLong
The byte count in the request body if it is both known and streamed; and
-1 otherwise. Prefer this field over the int-valued fixedContentLength on platforms that support both.
boolean instanceFollowRedirects
Flag to define whether the protocol will automatically follow redirects
or not. The default value is true.
String method
The HTTP request method of this HttpURLConnection. The default
value is "GET".
int responseCode
The status code of the response obtained from the HTTP request. The
default value is -1.
String responseMessage
The HTTP response message which corresponds to the response code.
HttpURLConnection (URL url)
Constructs a new HttpURLConnection instance pointing to the
resource specified by the url.
| Parameters | |
|---|---|
url |
URL:
the URL of this connection. |
See also:
void disconnect ()
Releases this connection so that its resources may be either reused or closed.
Unlike other Java implementations, this will not necessarily close
socket connections that can be reused. You can disable all connection
reuse by setting the http.keepAlive system property to false before issuing any HTTP requests.
String getContentEncoding ()
Returns the encoding used to transmit the response body over the network.
This is null or "identity" if the content was not encoded, or "gzip" if
the body was gzip compressed. Most callers will be more interested in the
content type, which may also include the
content's character encoding.
| Returns | |
|---|---|
String |
the value of the response header field content-encoding.
|
InputStream getErrorStream ()
Returns an input stream from the server in the case of an error such as the requested file has not been found on the remote server. This stream can be used to read the data the server will send back.
| Returns | |
|---|---|
InputStream |
the error input stream returned by the server. |
boolean getFollowRedirects ()
Returns the value of followRedirects which indicates if this
connection follows a different URL redirected by the server. It is
enabled by default.
| Returns | |
|---|---|
boolean |
the value of the flag. |
See also:
long getHeaderFieldDate (String field, long defaultValue)
Returns the date value in milliseconds since 01.01.1970, 00:00h
corresponding to the header field field. The defaultValue
will be returned if no such field can be found in the response header.
| Parameters | |
|---|---|
field |
String:
the header field name. |
defaultValue |
long:
the default value to use if the specified header field wont be
found. |
| Returns | |
|---|---|
long |
the header field represented in milliseconds since January 1, 1970 GMT. |
boolean getInstanceFollowRedirects ()
Returns whether this connection follows redirects.
| Returns | |
|---|---|
boolean |
true if this connection follows redirects, false
otherwise.
|
Permission getPermission ()
Returns the permission object (in this case SocketPermission)
with the host and the port number as the target name and "resolve, connect" as the action list. If the port number of this URL
instance is lower than 0 the port will be set to 80.
| Returns | |
|---|---|
Permission |
the permission object required for this connection. |
| Throws | |
|---|---|
IOException |
if an IO exception occurs during the creation of the permission object. |
String getRequestMethod ()
Returns the request method which will be used to make the request to the remote HTTP server. All possible methods of this HTTP implementation is listed in the class definition.
| Returns | |
|---|---|
String |
the request method string. |
See also:
int getResponseCode ()
Returns the response code returned by the remote HTTP server.
| Returns | |
|---|---|
int |
the response code, -1 if no valid response code. |
| Throws | |
|---|---|
IOException |
if there is an IO error during the retrieval. |
See also:
String getResponseMessage ()
Returns the response message returned by the remote HTTP server.
| Returns | |
|---|---|
String |
the response message. null if no such response exists. |
| Throws | |
|---|---|
IOException |
if there is an error during the retrieval. |
See also:
void setChunkedStreamingMode (int chunkLength)
Stream a request body whose length is not known in advance. Old HTTP/1.0 only servers may not support this mode.
When HTTP chunked encoding is used, the stream is divided into chunks, each prefixed with a header containing the chunk's size. A large chunk length requires a large internal buffer, potentially wasting memory. A small chunk length increases the number of bytes that must be transmitted because of the header on every chunk.
Implementation details: In some releases the chunkLength is
treated as a hint: chunks sent to the server may actually be larger or
smaller. To force a chunk to be sent to the server call
flush().
| Parameters | |
|---|---|
chunkLength |
int:
the length to use, or 0 for the default chunk
length. |
| Throws | |
|---|---|
IllegalStateException |
if already connected or another mode already set. |
See also:
void setFixedLengthStreamingMode (int contentLength)
Equivalent to setFixedLengthStreamingMode((long) contentLength),
but available on earlier versions of Android and limited to 2 GiB.
| Parameters | |
|---|---|
contentLength |
int
|
void setFixedLengthStreamingMode (long contentLength)
Configures this connection to stream the request body with the known
fixed byte count of contentLength.
| Parameters | |
|---|---|
contentLength |
long:
the fixed length of the HTTP request body. |
| Throws | |
|---|---|
IllegalStateException |
if already connected or another mode already set. |
IllegalArgumentException |
if contentLength is less than zero. |
See also:
void setFollowRedirects (boolean auto)
Sets the flag of whether this connection will follow redirects returned by the remote server.
| Parameters | |
|---|---|
auto |
boolean:
the value to enable or disable this option.
|
void setInstanceFollowRedirects (boolean followRedirects)
Sets whether this connection follows redirects.
| Parameters | |
|---|---|
followRedirects |
boolean:
true if this connection will follows redirects, false
otherwise.
|
void setRequestMethod (String method)
Sets the request command which will be sent to the remote HTTP server. This method can only be called before the connection is made.
| Parameters | |
|---|---|
method |
String:
the string representing the method to be used. |
| Throws | |
|---|---|
ProtocolException |
if this is called after connected, or the method is not supported by this HTTP implementation. |
See also:
boolean usingProxy ()
Returns whether this connection uses a proxy server or not.
| Returns | |
|---|---|
boolean |
true if this connection passes a proxy server, false
otherwise.
|