Class HttpURLConnection
- Direct Known Subclasses:
HttpsURLConnection,HttpURLConnectionImpl
public abstract class HttpURLConnection extends URLConnection
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:
- Obtain a new
HttpURLConnectionby callingURL.openConnection()and casting the result toHttpURLConnection. - Prepare the request. The primary property of a request is its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.
- Optionally upload a request body. Instances must be configured with
setDoOutput(true)if they include a request body. Transmit data by writing to the stream returned byURLConnection.getOutputStream(). - Read the response. Response headers typically include metadata such as
the response body's content type and length, modified dates and session
cookies. The response body may be read from the stream returned by
URLConnection.getInputStream(). If the response has no body, that method returns an empty stream. - Disconnect. Once the response body has been read, the
HttpURLConnectionshould be closed by callingdisconnect(). 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();
}
Secure Communication with HTTPS
CallingURL.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.
Response Handling
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, URLConnection.getInputStream() will throw an IOException. Use getErrorStream() to read the error response. The headers can be read in
the normal way using URLConnection.getHeaderFields(),
Posting Content
To upload data to a web server, configure the connection for output usingsetDoOutput(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();
}
Performance
The input and output streams returned by this class are not buffered. Most callers should wrap the returned streams withBufferedInputStream 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. Since URLConnection.getContentLength() returns the
number of bytes transmitted, you cannot use that method to predict how many
bytes can be read from URLConnection.getInputStream(). Instead, read that stream
until it is exhausted: when InputStream.read() returns -1. Gzip
compression can be disabled by setting the acceptable encodings in the
request header:
urlConnection.setRequestProperty("Accept-Encoding", "identity");
Handling Network Sign-On
Some Wi-Fi networks block Internet access until the user clicks through a sign-on page. Such sign-on pages are typically presented by using HTTP redirects. You can useURLConnection.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
URLConnection.getHeaderFields() or URLConnection.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();
}
HTTP Authentication
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.
Sessions with Cookies
To establish and maintain a potentially long-lived session between client and server,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: CookiePolicy.ACCEPT_ALL and CookiePolicy.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);
HTTP Methods
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(java.lang.String).
Proxies
By default, this class will connect directly to the origin server. It can also connect via anHTTP or SOCKS proxy. To use a proxy, use URL.openConnection(Proxy) when creating the
connection.
IPv6 Support
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.
Response Caching
Android 4.0 (Ice Cream Sandwich, API level 15) includes a response cache. Seeandroid.net.http.HttpResponseCache for instructions on enabling HTTP
caching in your application.
Avoiding Bugs In Earlier Releases
Prior to Android 2.2 (Froyo), this class had some frustrating bugs. In particular, callingclose() 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.
-
Field Summary
Fields Modifier and Type Field Description protected intchunkLengthIf the HTTP chunked encoding is enabled this parameter defines the chunk-length.protected intfixedContentLengthThe byte count in the request body if it is both known and streamed; and -1 otherwise.protected longfixedContentLengthLongThe byte count in the request body if it is both known and streamed; and -1 otherwise.static intHTTP_ACCEPTEDNumeric status code, 202: Acceptedstatic intHTTP_BAD_GATEWAYNumeric status code, 502: Bad Gatewaystatic intHTTP_BAD_METHODNumeric status code, 405: Bad Methodstatic intHTTP_BAD_REQUESTNumeric status code, 400: Bad Requeststatic intHTTP_CLIENT_TIMEOUTNumeric status code, 408: Client Timeoutstatic intHTTP_CONFLICTNumeric status code, 409: Conflictstatic intHTTP_CREATEDNumeric status code, 201: Createdstatic intHTTP_ENTITY_TOO_LARGENumeric status code, 413: Entity too largestatic intHTTP_FORBIDDENNumeric status code, 403: Forbiddenstatic intHTTP_GATEWAY_TIMEOUTNumeric status code, 504: Gateway timeoutstatic intHTTP_GONENumeric status code, 410: Gonestatic intHTTP_INTERNAL_ERRORNumeric status code, 500: Internal errorstatic intHTTP_LENGTH_REQUIREDNumeric status code, 411: Length requiredstatic intHTTP_MOVED_PERMNumeric status code, 301 Moved permanentlystatic intHTTP_MOVED_TEMPNumeric status code, 302: Moved temporarilystatic intHTTP_MULT_CHOICENumeric status code, 300: Multiple choicesstatic intHTTP_NO_CONTENTNumeric status code, 204: No contentstatic intHTTP_NOT_ACCEPTABLENumeric status code, 406: Not acceptablestatic intHTTP_NOT_AUTHORITATIVENumeric status code, 203: Not authoritativestatic intHTTP_NOT_FOUNDNumeric status code, 404: Not foundstatic intHTTP_NOT_IMPLEMENTEDNumeric status code, 501: Not implementedstatic intHTTP_NOT_MODIFIEDNumeric status code, 304: Not modifiedstatic intHTTP_OKNumeric status code, 200: OKstatic intHTTP_PARTIALNumeric status code, 206: Partialstatic intHTTP_PAYMENT_REQUIREDNumeric status code, 402: Payment requiredstatic intHTTP_PRECON_FAILEDNumeric status code, 412: Precondition failedstatic intHTTP_PROXY_AUTHNumeric status code, 407: Proxy authentication requiredstatic intHTTP_REQ_TOO_LONGNumeric status code, 414: Request too longstatic intHTTP_RESETNumeric status code, 205: Resetstatic intHTTP_SEE_OTHERNumeric status code, 303: See otherstatic intHTTP_SERVER_ERRORDeprecated.static intHTTP_UNAUTHORIZEDNumeric status code, 401: Unauthorizedstatic intHTTP_UNAVAILABLENumeric status code, 503: Unavailablestatic intHTTP_UNSUPPORTED_TYPENumeric status code, 415: Unsupported typestatic intHTTP_USE_PROXYNumeric status code, 305: Use proxy.static intHTTP_VERSIONNumeric status code, 505: Version not supportedprotected booleaninstanceFollowRedirectsFlag to define whether the protocol will automatically follow redirects or not.protected StringmethodThe HTTP request method of thisHttpURLConnection.protected intresponseCodeThe status code of the response obtained from the HTTP request.protected StringresponseMessageThe HTTP response message which corresponds to the response code.Fields inherited from class java.net.URLConnection
allowUserInteraction, connected, doInput, doOutput, ifModifiedSince, url, useCaches -
Constructor Summary
Constructors Modifier Constructor Description protectedHttpURLConnection(URL url)Constructs a newHttpURLConnectioninstance pointing to the resource specified by theurl. -
Method Summary
Modifier and Type Method Description abstract voiddisconnect()Releases this connection so that its resources may be either reused or closed.StringgetContentEncoding()Returns the encoding used to transmit the response body over the network.InputStreamgetErrorStream()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 booleangetFollowRedirects()Returns the value offollowRedirectswhich indicates if this connection follows a different URL redirected by the server.longgetHeaderFieldDate(String field, long defaultValue)Returns the date value in milliseconds since01.01.1970, 00:00hcorresponding to the header fieldfield.booleangetInstanceFollowRedirects()Returns whether this connection follows redirects.PermissiongetPermission()Returns the permission object (in this caseSocketPermission) with the host and the port number as the target name and"resolve, connect"as the action list.StringgetRequestMethod()Returns the request method which will be used to make the request to the remote HTTP server.intgetResponseCode()Returns the response code returned by the remote HTTP server.StringgetResponseMessage()Returns the response message returned by the remote HTTP server.voidsetChunkedStreamingMode(int chunkLength)Stream a request body whose length is not known in advance.voidsetFixedLengthStreamingMode(int contentLength)Equivalent tosetFixedLengthStreamingMode((long) contentLength), but available on earlier versions of Android and limited to 2 GiB.voidsetFixedLengthStreamingMode(long contentLength)Configures this connection to stream the request body with the known fixed byte count ofcontentLength.static voidsetFollowRedirects(boolean auto)Sets the flag of whether this connection will follow redirects returned by the remote server.voidsetInstanceFollowRedirects(boolean followRedirects)Sets whether this connection follows redirects.voidsetRequestMethod(String method)Sets the request command which will be sent to the remote HTTP server.abstract booleanusingProxy()Returns whether this connection uses a proxy server or not.Methods inherited from class java.net.URLConnection
addRequestProperty, connect, getAllowUserInteraction, getConnectTimeout, getContent, getContent, getContentLength, getContentType, getDate, getDefaultAllowUserInteraction, getDefaultRequestProperty, getDefaultUseCaches, getDoInput, getDoOutput, getExpiration, getFileNameMap, getHeaderField, getHeaderField, getHeaderFieldInt, getHeaderFieldKey, getHeaderFields, getIfModifiedSince, getInputStream, getLastModified, getOutputStream, getReadTimeout, getRequestProperties, getRequestProperty, getURL, getUseCaches, guessContentTypeFromName, guessContentTypeFromStream, setAllowUserInteraction, setConnectTimeout, setContentHandlerFactory, setDefaultAllowUserInteraction, setDefaultRequestProperty, setDefaultUseCaches, setDoInput, setDoOutput, setFileNameMap, setIfModifiedSince, setReadTimeout, setRequestProperty, setUseCaches, toString
-
Field Details
-
method
The HTTP request method of thisHttpURLConnection. The default value is"GET". -
responseCode
protected int responseCodeThe status code of the response obtained from the HTTP request. The default value is-1.- 1xx: Informational
- 2xx: Success
- 3xx: Relocation/Redirection
- 4xx: Client Error
- 5xx: Server Error
-
responseMessage
The HTTP response message which corresponds to the response code. -
instanceFollowRedirects
protected boolean instanceFollowRedirectsFlag to define whether the protocol will automatically follow redirects or not. The default value istrue. -
chunkLength
protected int chunkLengthIf the HTTP chunked encoding is enabled this parameter defines the chunk-length. Default value is-1that means the chunked encoding mode is disabled. -
fixedContentLength
protected int fixedContentLengthThe byte count in the request body if it is both known and streamed; and -1 otherwise. If the byte count exceedsInteger.MAX_VALUE(2 GiB) then the value of this field will beInteger.MAX_VALUE. In that case usefixedContentLengthLongto access the exact byte count. -
fixedContentLengthLong
protected long fixedContentLengthLongThe byte count in the request body if it is both known and streamed; and -1 otherwise. Prefer this field over theint-valuedfixedContentLengthon platforms that support both. -
HTTP_ACCEPTED
public static final int HTTP_ACCEPTEDNumeric status code, 202: Accepted- See Also:
- Constant Field Values
-
HTTP_BAD_GATEWAY
public static final int HTTP_BAD_GATEWAYNumeric status code, 502: Bad Gateway- See Also:
- Constant Field Values
-
HTTP_BAD_METHOD
public static final int HTTP_BAD_METHODNumeric status code, 405: Bad Method- See Also:
- Constant Field Values
-
HTTP_BAD_REQUEST
public static final int HTTP_BAD_REQUESTNumeric status code, 400: Bad Request- See Also:
- Constant Field Values
-
HTTP_CLIENT_TIMEOUT
public static final int HTTP_CLIENT_TIMEOUTNumeric status code, 408: Client Timeout- See Also:
- Constant Field Values
-
HTTP_CONFLICT
public static final int HTTP_CONFLICTNumeric status code, 409: Conflict- See Also:
- Constant Field Values
-
HTTP_CREATED
public static final int HTTP_CREATEDNumeric status code, 201: Created- See Also:
- Constant Field Values
-
HTTP_ENTITY_TOO_LARGE
public static final int HTTP_ENTITY_TOO_LARGENumeric status code, 413: Entity too large- See Also:
- Constant Field Values
-
HTTP_FORBIDDEN
public static final int HTTP_FORBIDDENNumeric status code, 403: Forbidden- See Also:
- Constant Field Values
-
HTTP_GATEWAY_TIMEOUT
public static final int HTTP_GATEWAY_TIMEOUTNumeric status code, 504: Gateway timeout- See Also:
- Constant Field Values
-
HTTP_GONE
public static final int HTTP_GONENumeric status code, 410: Gone- See Also:
- Constant Field Values
-
HTTP_INTERNAL_ERROR
public static final int HTTP_INTERNAL_ERRORNumeric status code, 500: Internal error- See Also:
- Constant Field Values
-
HTTP_LENGTH_REQUIRED
public static final int HTTP_LENGTH_REQUIREDNumeric status code, 411: Length required- See Also:
- Constant Field Values
-
HTTP_MOVED_PERM
public static final int HTTP_MOVED_PERMNumeric status code, 301 Moved permanently- See Also:
- Constant Field Values
-
HTTP_MOVED_TEMP
public static final int HTTP_MOVED_TEMPNumeric status code, 302: Moved temporarily- See Also:
- Constant Field Values
-
HTTP_MULT_CHOICE
public static final int HTTP_MULT_CHOICENumeric status code, 300: Multiple choices- See Also:
- Constant Field Values
-
HTTP_NO_CONTENT
public static final int HTTP_NO_CONTENTNumeric status code, 204: No content- See Also:
- Constant Field Values
-
HTTP_NOT_ACCEPTABLE
public static final int HTTP_NOT_ACCEPTABLENumeric status code, 406: Not acceptable- See Also:
- Constant Field Values
-
HTTP_NOT_AUTHORITATIVE
public static final int HTTP_NOT_AUTHORITATIVENumeric status code, 203: Not authoritative- See Also:
- Constant Field Values
-
HTTP_NOT_FOUND
public static final int HTTP_NOT_FOUNDNumeric status code, 404: Not found- See Also:
- Constant Field Values
-
HTTP_NOT_IMPLEMENTED
public static final int HTTP_NOT_IMPLEMENTEDNumeric status code, 501: Not implemented- See Also:
- Constant Field Values
-
HTTP_NOT_MODIFIED
public static final int HTTP_NOT_MODIFIEDNumeric status code, 304: Not modified- See Also:
- Constant Field Values
-
HTTP_OK
public static final int HTTP_OKNumeric status code, 200: OK- See Also:
- Constant Field Values
-
HTTP_PARTIAL
public static final int HTTP_PARTIALNumeric status code, 206: Partial- See Also:
- Constant Field Values
-
HTTP_PAYMENT_REQUIRED
public static final int HTTP_PAYMENT_REQUIREDNumeric status code, 402: Payment required- See Also:
- Constant Field Values
-
HTTP_PRECON_FAILED
public static final int HTTP_PRECON_FAILEDNumeric status code, 412: Precondition failed- See Also:
- Constant Field Values
-
HTTP_PROXY_AUTH
public static final int HTTP_PROXY_AUTHNumeric status code, 407: Proxy authentication required- See Also:
- Constant Field Values
-
HTTP_REQ_TOO_LONG
public static final int HTTP_REQ_TOO_LONGNumeric status code, 414: Request too long- See Also:
- Constant Field Values
-
HTTP_RESET
public static final int HTTP_RESETNumeric status code, 205: Reset- See Also:
- Constant Field Values
-
HTTP_SEE_OTHER
public static final int HTTP_SEE_OTHERNumeric status code, 303: See other- See Also:
- Constant Field Values
-
HTTP_SERVER_ERROR
Deprecated.UseHTTP_INTERNAL_ERRORinstead.Numeric status code, 500: Internal error- See Also:
- Constant Field Values
-
HTTP_USE_PROXY
public static final int HTTP_USE_PROXYNumeric 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.
- See Also:
- Constant Field Values
-
HTTP_UNAUTHORIZED
public static final int HTTP_UNAUTHORIZEDNumeric status code, 401: Unauthorized- See Also:
- Constant Field Values
-
HTTP_UNSUPPORTED_TYPE
public static final int HTTP_UNSUPPORTED_TYPENumeric status code, 415: Unsupported type- See Also:
- Constant Field Values
-
HTTP_UNAVAILABLE
public static final int HTTP_UNAVAILABLENumeric status code, 503: Unavailable- See Also:
- Constant Field Values
-
HTTP_VERSION
public static final int HTTP_VERSIONNumeric status code, 505: Version not supported- See Also:
- Constant Field Values
-
-
Constructor Details
-
HttpURLConnection
Constructs a newHttpURLConnectioninstance pointing to the resource specified by theurl.- Parameters:
url- the URL of this connection.- See Also:
URL,URLConnection
-
-
Method Details
-
disconnect
public abstract 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.keepAlivesystem property tofalsebefore issuing any HTTP requests. -
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:
- the error input stream returned by the server.
-
getFollowRedirects
public static boolean getFollowRedirects()Returns the value offollowRedirectswhich indicates if this connection follows a different URL redirected by the server. It is enabled by default.- Returns:
- the value of the flag.
- See Also:
setFollowRedirects(boolean)
-
getPermission
Returns the permission object (in this caseSocketPermission) 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 than0the port will be set to80.- Overrides:
getPermissionin classURLConnection- Returns:
- the permission object required for this connection.
- Throws:
IOException- if an IO exception occurs during the creation of the permission object.
-
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:
- the request method string.
- See Also:
method,setRequestMethod(java.lang.String)
-
getResponseCode
Returns the response code returned by the remote HTTP server.- Returns:
- the response code, -1 if no valid response code.
- Throws:
IOException- if there is an IO error during the retrieval.- See Also:
getResponseMessage()
-
getResponseMessage
Returns the response message returned by the remote HTTP server.- Returns:
- the response message.
nullif no such response exists. - Throws:
IOException- if there is an error during the retrieval.- See Also:
getResponseCode()
-
setFollowRedirects
public static void setFollowRedirects(boolean auto)Sets the flag of whether this connection will follow redirects returned by the remote server.- Parameters:
auto- the value to enable or disable this option.
-
setRequestMethod
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- 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:
getRequestMethod(),method
-
usingProxy
public abstract boolean usingProxy()Returns whether this connection uses a proxy server or not.- Returns:
trueif this connection passes a proxy server, false otherwise.
-
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 thecontent type, which may also include the content's character encoding.- Overrides:
getContentEncodingin classURLConnection- Returns:
- the value of the response header field
content-encoding.
-
getInstanceFollowRedirects
public boolean getInstanceFollowRedirects()Returns whether this connection follows redirects.- Returns:
trueif this connection follows redirects, false otherwise.
-
setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)Sets whether this connection follows redirects.- Parameters:
followRedirects-trueif this connection will follows redirects, false otherwise.
-
getHeaderFieldDate
Returns the date value in milliseconds since01.01.1970, 00:00hcorresponding to the header fieldfield. ThedefaultValuewill be returned if no such field can be found in the response header.- Overrides:
getHeaderFieldDatein classURLConnection- Parameters:
field- the header field name.defaultValue- the default value to use if the specified header field wont be found.- Returns:
- the header field represented in milliseconds since January 1, 1970 GMT.
-
setFixedLengthStreamingMode
public void setFixedLengthStreamingMode(long contentLength)Configures this connection to stream the request body with the known fixed byte count ofcontentLength.- Parameters:
contentLength- the fixed length of the HTTP request body.- Throws:
IllegalStateException- if already connected or another mode already set.IllegalArgumentException- ifcontentLengthis less than zero.- Since:
- 1.7
- See Also:
setChunkedStreamingMode(int)
-
setFixedLengthStreamingMode
public void setFixedLengthStreamingMode(int contentLength)Equivalent tosetFixedLengthStreamingMode((long) contentLength), but available on earlier versions of Android and limited to 2 GiB. -
setChunkedStreamingMode
public 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. Setting a large chunk length requires a large internal buffer, potentially wasting memory. Setting a small chunk length increases the number of bytes that must be transmitted because of the header on every chunk. Most caller should use
0to get the system default.- Parameters:
chunkLength- the length to use, or0for the default chunk length.- Throws:
IllegalStateException- if already connected or another mode already set.- See Also:
setFixedLengthStreamingMode(long)
-
HTTP_INTERNAL_ERRORinstead.