Android Guides | Samples

Java.Net.HttpURLConnection Class

An URLConnection for HTTP () used to send and receive data over the web.

See Also: HttpURLConnection

Syntax

[Android.Runtime.Register("java/net/HttpURLConnection", DoNotGenerateAcw=true)]
public abstract class HttpURLConnection : URLConnection

Remarks

An URLConnection for HTTP () 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:

  1. Obtain a new HttpURLConnection by calling URL.OpenConnection and casting the result to HttpURLConnection.
  2. 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.
  3. Optionally upload a request body. Instances must be configured with URLConnection.DoOutput if they include a request body. Transmit data by writing to the stream returned by URLConnection.OutputStream.
  4. 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.InputStream. If the response has no body, that method returns an empty stream.
  5. Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling HttpURLConnection.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/:

java Example

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

Calling URL.OpenConnection on a URL with the "https" scheme will return an HttpsURLConnection, which allows for overriding the default IHostnameVerifier and SSLSocketFactory. An application-supplied SSLSocketFactory created from an SSLContext can provide a custom IX509TrustManager for verifying certificate chains and a custom IX509KeyManager 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.InputStream will throw an IOException. Use HttpURLConnection.ErrorStream to read the error response. The headers can be read in the normal way using URLConnection.HeaderFields,

Posting Content

To upload data to a web server, configure the connection for output using URLConnection.DoOutput.

For best performance, you should call either HttpURLConnection.SetFixedLengthStreamingMode(Int32) when the body length is known in advance, or HttpURLConnection.SetChunkedStreamingMode(Int32) 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:

java Example

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 with 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 HttpURLConnection.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 URLConnection.InputStream. 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:

java Example

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.

URLConnection.ContentLength returns the number of bytes transmitted and cannot be used to predict how many bytes can be read from URLConnection.InputStream for compressed streams. Instead, read that stream until it is exhausted, i.e. when InputStream.Read returns -1.

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 use URLConnection.URL 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.HeaderFields or URLConnection.InputStream. For example, to check that a response was not redirected to an unexpected host:

java Example

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 . Use Authenticator to set the VM-wide authentication handler:

java Example

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:

java Example

CookieManager cookieManager = new CookieManager();
   CookieHandler.setDefault(cookieManager);
By default, CookieManager accepts cookies from the only. Two other policies are included: CookiePolicy.AcceptAll and CookiePolicy.AcceptNone. 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 ICookieStore 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 cookies. Many web servers support only the older specification, . For compatibility with the most web servers, set the cookie version to 0.

For example, to receive www.twitter.com in French:

java Example

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 URLConnection.DoOutput has been called. Other HTTP methods (OPTIONS, HEAD, PUT, DELETE and TRACE) can be used with HttpURLConnection.RequestMethod.

Proxies

By default, this class will connect directly to the . It can also connect via an NoType:java/net/Proxy$Type;Href=../../../reference/java/net/Proxy.Type.html#HTTP or NoType:java/net/Proxy$Type;Href=../../../reference/java/net/Proxy.Type.html#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. See android.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, calling close() on a readable InputStream could . Work around this by disabling connection pooling:

java Example

private void disableConnectionReuseIfNecessary() {
   // Work around pre-Froyo bugs in HTTP connection reuse.
   if (Integer.parseInt(Build.VERSION.SDK) 
 }}

Each instance of HttpURLConnection may be used for one request/response pair. Instances of this class are not thread safe.

[Android Documentation]

Requirements

Namespace: Java.Net
Assembly: Mono.Android (in Mono.Android.dll)
Assembly Versions: 0.0.0.0
Since: Added in API level 1

The members of Java.Net.HttpURLConnection are listed below.

See Also: URLConnection

Protected Constructors

Constructs a new HttpURLConnection instance pointing to the resource specified by the url.
A constructor used when creating managed representations of JNI objects; called by the runtime.

Public Fields

const
HttpAcceptedHttpStatus (202). Numeric status code, 202: Accepted
const
HttpBadGatewayHttpStatus (502). Numeric status code, 502: Bad Gateway
const
HttpBadMethodHttpStatus (405). Numeric status code, 405: Bad Method
const
HttpBadRequestHttpStatus (400). Numeric status code, 400: Bad Request
const
HttpClientTimeoutHttpStatus (408). Numeric status code, 408: Client Timeout
const
HttpConflictHttpStatus (409). Numeric status code, 409: Conflict
const
HttpCreatedHttpStatus (201). Numeric status code, 201: Created
const
HttpEntityTooLargeHttpStatus (413). Numeric status code, 413: Entity too large
const
HttpForbiddenHttpStatus (403). Numeric status code, 403: Forbidden
const
HttpGatewayTimeoutHttpStatus (504). Numeric status code, 504: Gateway timeout
const
HttpGoneHttpStatus (410). Numeric status code, 410: Gone
const
HttpInternalErrorHttpStatus (500). Numeric status code, 500: Internal error
const
HttpLengthRequiredHttpStatus (411). Numeric status code, 411: Length required
const
HttpMovedPermHttpStatus (301). Numeric status code, 301 Moved permanently
const
HttpMovedTempHttpStatus (302). Numeric status code, 302: Moved temporarily
const
HttpMultChoiceHttpStatus (300). Numeric status code, 300: Multiple choices
const
HttpNoContentHttpStatus (204). Numeric status code, 204: No content
const
HttpNotAcceptableHttpStatus (406). Numeric status code, 406: Not acceptable
const
HttpNotAuthoritativeHttpStatus (203). Numeric status code, 203: Not authoritative
const
HttpNotFoundHttpStatus (404). Numeric status code, 404: Not found
const
HttpNotImplementedHttpStatus (501). Numeric status code, 501: Not implemented
const
HttpNotModifiedHttpStatus (304). Numeric status code, 304: Not modified
const
HttpOkHttpStatus (200). Numeric status code, 200: OK
const
HttpPartialHttpStatus (206). Numeric status code, 206: Partial
const
HttpPaymentRequiredHttpStatus (402). Numeric status code, 402: Payment required
const
HttpPreconFailedHttpStatus (412). Numeric status code, 412: Precondition failed
const
HttpProxyAuthHttpStatus (407). Numeric status code, 407: Proxy authentication required
const
HttpReqTooLongHttpStatus (414). Numeric status code, 414: Request too long
const
HttpResetHttpStatus (205). Numeric status code, 205: Reset
const
HttpSeeOtherHttpStatus (303). Numeric status code, 303: See other
const
HttpServerErrorHttpStatus (500). Numeric status code, 500: Internal error
const
HttpUnauthorizedHttpStatus (401). Numeric status code, 401: Unauthorized
const
HttpUnavailableHttpStatus (503). Numeric status code, 503: Unavailable
const
HttpUnsupportedTypeHttpStatus (415). Numeric status code, 415: Unsupported type
const
HttpUseProxyHttpStatus (305). Numeric status code, 305: Use proxy.
const
HttpVersionHttpStatus (505). Numeric status code, 505: Version not supported

Public Properties

[read-only]
ErrorStreamStream. 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
FollowRedirectsBoolean. Returns the value of followRedirects which indicates if this connection follows a different URL redirected by the server.
InstanceFollowRedirectsBoolean. Returns whether this connection follows redirects.
RequestMethodString. Returns the request method which will be used to make the request to the remote HTTP server.
[read-only]
ResponseCodeHttpStatus. Returns the response code returned by the remote HTTP server.
[read-only]
ResponseMessageString. Returns the response message returned by the remote HTTP server.

Protected Properties

ChunkLengthInt32. If the HTTP chunked encoding is enabled this parameter defines the chunk-length.
FixedContentLengthInt32. The byte count in the request body if it is both known and streamed; and -1 otherwise.
FixedContentLengthLongInt64. The byte count in the request body if it is both known and streamed; and -1 otherwise.
MethodString. The HTTP request method of this HttpURLConnection.
[read-only]
override
ThresholdClassIntPtr. This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
[read-only]
override
ThresholdTypeType. This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Public Methods

abstract
Disconnect()
Releases this connection so that its resources may be either reused or closed.
SetChunkedStreamingMode(Int32)
Stream a request body whose length is not known in advance.
SetFixedLengthStreamingMode(Int32)
Equivalent to setFixedLengthStreamingMode((long) contentLength), but available on earlier versions of Android and limited to 2 GiB.
SetFixedLengthStreamingMode(Int64)
Configures this connection to stream the request body with the known fixed byte count of contentLength.
abstract
UsingProxy() : Boolean
Returns whether this connection uses a proxy server or not.