Share via


HttpURLConnection Class

Definition

A URLConnection with support for HTTP-specific features.

[Android.Runtime.Register("java/net/HttpURLConnection", DoNotGenerateAcw=true)]
public abstract class HttpURLConnection : Java.Net.URLConnection
[<Android.Runtime.Register("java/net/HttpURLConnection", DoNotGenerateAcw=true)>]
type HttpURLConnection = class
    inherit URLConnection
Inheritance
HttpURLConnection
Derived
Attributes

Remarks

A URLConnection with support for HTTP-specific features. See the spec for details.

Uses of this class follow a pattern: <ol> <li>Obtain a new HttpURLConnection by calling URL#openConnection() URL.openConnection() and casting the result to HttpURLConnection. <li>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. <li>Optionally upload a request body. Instances must be configured with #setDoOutput(boolean) setDoOutput(true) if they include a request body. Transmit data by writing to the stream returned by #getOutputStream(). <li>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 #getInputStream(). If the response has no body, that method returns an empty stream. <li>Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling #disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused. </ol>

For example, to retrieve the webpage at http://www.android.com/:

{@code
              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();
              }
            }

<h3>Secure Communication with HTTPS</h3> Calling URL#openConnection() on a URL with the "https" scheme will return an HttpsURLConnection, which allows for overriding the default javax.net.ssl.HostnameVerifier HostnameVerifier and javax.net.ssl.SSLSocketFactory SSLSocketFactory. An application-supplied SSLSocketFactory created from an javax.net.ssl.SSLContext SSLContext can provide a custom javax.net.ssl.X509TrustManager X509TrustManager for verifying certificate chains and a custom javax.net.ssl.X509KeyManager X509KeyManager for supplying client certificates. See javax.net.ssl.HttpsURLConnection HttpsURLConnection for more details.

<h3>Response Handling</h3> 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(),

<h3>Posting Content</h3> To upload data to a web server, configure the connection for output using #setDoOutput(boolean) 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:

{@code
              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();
              }
            }

<h3>Performance</h3> The input and output streams returned by this class are <strong>not buffered</strong>. Most callers should wrap the returned streams with java.io.BufferedInputStream BufferedInputStream or java.io.BufferedOutputStream 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.

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:

{@code
              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 InputStream#read returns -1.

<h3>Handling Network Sign-On</h3> 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 #getURL() to test if your connection has been unexpectedly redirected. This check is not valid until <strong>after</strong> 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:

{@code
              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();
              }
            }

<h3>HTTP Authentication</h3> HttpURLConnection supports HTTP basic authentication. Use Authenticator to set the VM-wide authentication handler:

{@code
              Authenticator.setDefault(new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(username, password.toCharArray());
                }
              });
            }

Unless paired with HTTPS, this is <strong>not</strong> a secure mechanism for user authentication. In particular, the username, password, request and response are all transmitted over the network without encryption.

<h3>Sessions with Cookies</h3> 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:

{@code
              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:

{@code
              HttpCookie cookie = new HttpCookie("lang", "fr");
              cookie.setDomain("twitter.com");
              cookie.setPath("/");
              cookie.setVersion(0);
              cookieManager.getCookieStore().add(new URI("http://twitter.com/"), cookie);
            }

<h3>HTTP Methods</h3>

HttpURLConnection uses the GET method by default. It will use POST if #setDoOutput setDoOutput(true) has been called. Other HTTP methods (OPTIONS, HEAD, PUT, DELETE and TRACE) can be used with #setRequestMethod.

<h3>Proxies</h3> By default, this class will connect directly to the origin server. It can also connect via an Proxy.Type#HTTP HTTP or Proxy.Type#SOCKS SOCKS proxy. To use a proxy, use URL#openConnection(Proxy) URL.openConnection(Proxy) when creating the connection.

<h3>IPv6 Support</h3>

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.

<h3>Response Caching</h3> 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.

<h3>Avoiding Bugs In Earlier Releases</h3> Prior to Android 2.2 (Froyo), this class had some frustrating bugs. In particular, calling close() on a readable InputStream could poison the connection pool. Work around this by disabling connection pooling:

{@code
            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.

Added in JDK1.1.

Java documentation for java.net.HttpURLConnection.

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

HttpURLConnection(IntPtr, JniHandleOwnership)

A constructor used when creating managed representations of JNI objects; called by the runtime.

HttpURLConnection(URL)

Constructor for the HttpURLConnection.

Fields

HttpAccepted
Obsolete.

HTTP Status-Code 202: Accepted.

HttpBadGateway
Obsolete.

HTTP Status-Code 502: Bad Gateway.

HttpBadMethod
Obsolete.

HTTP Status-Code 405: Method Not Allowed.

HttpBadRequest
Obsolete.

HTTP Status-Code 400: Bad Request.

HttpClientTimeout
Obsolete.

HTTP Status-Code 408: Request Time-Out.

HttpConflict
Obsolete.

HTTP Status-Code 409: Conflict.

HttpCreated
Obsolete.

HTTP Status-Code 201: Created.

HttpEntityTooLarge
Obsolete.

HTTP Status-Code 413: Request Entity Too Large.

HttpForbidden
Obsolete.

HTTP Status-Code 403: Forbidden.

HttpGatewayTimeout
Obsolete.

HTTP Status-Code 504: Gateway Timeout.

HttpGone
Obsolete.

HTTP Status-Code 410: Gone.

HttpInternalError
Obsolete.

HTTP Status-Code 500: Internal Server Error.

HttpLengthRequired
Obsolete.

HTTP Status-Code 411: Length Required.

HttpMovedPerm
Obsolete.

HTTP Status-Code 301: Moved Permanently.

HttpMovedTemp
Obsolete.

HTTP Status-Code 302: Temporary Redirect.

HttpMultChoice
Obsolete.

HTTP Status-Code 300: Multiple Choices.

HttpNoContent
Obsolete.

HTTP Status-Code 204: No Content.

HttpNotAcceptable
Obsolete.

HTTP Status-Code 406: Not Acceptable.

HttpNotAuthoritative
Obsolete.

HTTP Status-Code 203: Non-Authoritative Information.

HttpNotFound
Obsolete.

HTTP Status-Code 404: Not Found.

HttpNotImplemented
Obsolete.

HTTP Status-Code 501: Not Implemented.

HttpNotModified
Obsolete.

HTTP Status-Code 304: Not Modified.

HttpOk
Obsolete.

HTTP Status-Code 200: OK.

HttpPartial
Obsolete.

HTTP Status-Code 206: Partial Content.

HttpPaymentRequired
Obsolete.

HTTP Status-Code 402: Payment Required.

HttpPreconFailed
Obsolete.

HTTP Status-Code 412: Precondition Failed.

HttpProxyAuth
Obsolete.

HTTP Status-Code 407: Proxy Authentication Required.

HttpReqTooLong
Obsolete.

HTTP Status-Code 414: Request-URI Too Large.

HttpReset
Obsolete.

HTTP Status-Code 205: Reset Content.

HttpSeeOther
Obsolete.

HTTP Status-Code 303: See Other.

HttpServerError
Obsolete.

HTTP Status-Code 500: Internal Server Error.

HttpUnauthorized
Obsolete.

HTTP Status-Code 401: Unauthorized.

HttpUnavailable
Obsolete.

HTTP Status-Code 503: Service Unavailable.

HttpUnsupportedType
Obsolete.

HTTP Status-Code 415: Unsupported Media Type.

HttpUseProxy
Obsolete.

HTTP Status-Code 305: Use Proxy.

HttpVersion
Obsolete.

HTTP Status-Code 505: HTTP Version Not Supported.

Properties

AllowUserInteraction

Returns the value of the allowUserInteraction field for this object. -or- Set the value of the allowUserInteraction field of this URLConnection.

(Inherited from URLConnection)
ChunkLength

The chunk-length when using chunked encoding streaming mode for output.

Class

Returns the runtime class of this Object.

(Inherited from Object)
Connected

If false, this connection object has not created a communications link to the specified URL.

(Inherited from URLConnection)
ConnectTimeout

Returns setting for connect timeout. -or- Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.

(Inherited from URLConnection)
Content

Retrieves the contents of this URL connection.

(Inherited from URLConnection)
ContentEncoding

Returns the value of the content-encoding header field.

(Inherited from URLConnection)
ContentLength

Returns the value of the content-length header field.

(Inherited from URLConnection)
ContentLengthLong

Returns the value of the content-length header field as a long.

(Inherited from URLConnection)
ContentType

Returns the value of the content-type header field.

(Inherited from URLConnection)
Date

Returns the value of the date header field.

(Inherited from URLConnection)
DefaultUseCaches

Returns the default value of a URLConnection's useCaches flag. -or- Sets the default value of the useCaches field to the specified value.

(Inherited from URLConnection)
DoInput

Returns the value of this URLConnection's doInput flag. -or- Sets the value of the doInput field for this URLConnection to the specified value.

(Inherited from URLConnection)
DoOutput

Returns the value of this URLConnection's doOutput flag. -or- Sets the value of the doOutput field for this URLConnection to the specified value.

(Inherited from URLConnection)
ErrorStream

Returns the error stream if the connection failed but the server sent useful data nonetheless.

Expiration

Returns the value of the expires header field.

(Inherited from URLConnection)
FixedContentLength

The fixed content-length when using fixed-length streaming mode.

FixedContentLengthLong

The fixed content-length when using fixed-length streaming mode.

FollowRedirects

Returns a boolean indicating whether or not HTTP redirects (3xx) should be automatically followed. -or- Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.

Handle

The handle to the underlying Android instance.

(Inherited from Object)
HeaderFields

Returns an unmodifiable Map of the header fields.

(Inherited from URLConnection)
IfModifiedSince

Returns the value of this object's ifModifiedSince field. -or- Sets the value of the ifModifiedSince field of this URLConnection to the specified value.

(Inherited from URLConnection)
InputStream

Returns an input stream that reads from this open connection.

(Inherited from URLConnection)
InstanceFollowRedirects

Returns the value of this HttpURLConnection's instanceFollowRedirects field. -or- Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

JniIdentityHashCode (Inherited from Object)
JniPeerMembers
LastModified

Returns the value of the last-modified header field.

(Inherited from URLConnection)
Method

The HTTP method (GET,POST,PUT,etc.

OutputStream

Returns an output stream that writes to this connection.

(Inherited from URLConnection)
PeerReference (Inherited from Object)
Permission

Returns a permission object representing the permission necessary to make the connection represented by this object.

(Inherited from URLConnection)
ReadTimeout

Returns setting for read timeout. -or- Sets the read timeout to a specified timeout, in milliseconds.

(Inherited from URLConnection)
RequestMethod

Get the request method. -or- Set the method for the URL request, one of: <UL> <LI>GET <LI>POST <LI>HEAD <LI>OPTIONS <LI>PUT <LI>DELETE <LI>TRACE </UL> are legal, subject to protocol restrictions.

RequestProperties

Returns an unmodifiable Map of general request properties for this connection.

(Inherited from URLConnection)
ResponseCode

Gets the status code from an HTTP response message.

ResponseMessage

Gets the HTTP response message, if any, returned along with the response code from a server.

ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

ThresholdType

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Url

The URL represents the remote object on the World Wide Web to which this connection is opened.

(Inherited from URLConnection)
URL

Returns the value of this URLConnection's URL field.

(Inherited from URLConnection)
UseCaches

Returns the value of this URLConnection's useCaches field. -or- Sets the value of the useCaches field of this URLConnection to the specified value.

(Inherited from URLConnection)

Methods

AddRequestProperty(String, String)

Adds a general request property specified by a key-value pair.

(Inherited from URLConnection)
Clone()

Creates and returns a copy of this object.

(Inherited from Object)
Connect()

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

(Inherited from URLConnection)
ConnectAsync() (Inherited from URLConnection)
Disconnect()

Indicates that other requests to the server are unlikely in the near future.

Dispose() (Inherited from Object)
Dispose(Boolean) (Inherited from Object)
Equals(Object)

Indicates whether some other object is "equal to" this one.

(Inherited from Object)
GetContent(Class[])

Retrieves the contents of this URL connection.

(Inherited from URLConnection)
GetHashCode()

Returns a hash code value for the object.

(Inherited from Object)
GetHeaderField(Int32)

Returns the value for the n<sup>th</sup> header field.

(Inherited from URLConnection)
GetHeaderField(String)

Returns the value of the named header field.

(Inherited from URLConnection)
GetHeaderFieldDate(String, Int64)

Returns the value of the named field parsed as date.

(Inherited from URLConnection)
GetHeaderFieldInt(String, Int32)

Returns the value of the named field parsed as a number.

(Inherited from URLConnection)
GetHeaderFieldKey(Int32)

Returns the key for the n<sup>th</sup> header field.

(Inherited from URLConnection)
GetHeaderFieldLong(String, Int64)

Returns the value of the named field parsed as a number.

(Inherited from URLConnection)
GetRequestProperty(String)

Returns the value of the named general request property for this connection.

(Inherited from URLConnection)
JavaFinalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

(Inherited from Object)
Notify()

Wakes up a single thread that is waiting on this object's monitor.

(Inherited from Object)
NotifyAll()

Wakes up all threads that are waiting on this object's monitor.

(Inherited from Object)
SetChunkedStreamingMode(Int32)

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is <b>not</b> known in advance.

SetFixedLengthStreamingMode(Int32)

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

SetFixedLengthStreamingMode(Int64)

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Object)
SetRequestProperty(String, String)

Sets the general request property.

(Inherited from URLConnection)
ToArray<T>() (Inherited from Object)
ToString()

Returns a string representation of the object.

(Inherited from Object)
UnregisterFromRuntime() (Inherited from Object)
UsingProxy()

Indicates if the connection is going through a proxy.

Wait()

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>.

(Inherited from Object)
Wait(Int64, Int32)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)
Wait(Int64)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Object)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Object)
IJavaPeerable.Finalized() (Inherited from Object)
IJavaPeerable.JniManagedPeerState (Inherited from Object)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Object)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Object)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Object)

Extension Methods

JavaCast<TResult>(IJavaObject)

Performs an Android runtime-checked type conversion.

JavaCast<TResult>(IJavaObject)
GetJniTypeName(IJavaPeerable)

Applies to