See Also: HttpURLConnection Members
An Java.Net.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:
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(); } }
If the HTTP response indicates that an error occurred, URLConnection.InputStream will throw an Java.IO.IOException. Use HttpURLConnection.ErrorStream to read the error response. The headers can be read in the normal way using URLConnection.HeaderFields,
For best performance, you should call either HttpURLConnection.SetFixedLengthStreamingMode(int) when the body length is known in advance, or HttpURLConnection.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:
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(); } }
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. Since URLConnection.ContentLength returns the number of bytes transmitted, you cannot use that method to predict how many bytes can be read from URLConnection.InputStream. Instead, read that stream until it is exhausted: when Java.IO.InputStream.Read returns -1. Gzip compression can be disabled by setting the acceptable encodings in the request header:
java Example
urlConnection.setRequestProperty("Accept-Encoding", "identity");
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(); } }
java Example
Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password.toCharArray()); }); }
java Example
CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager);
The default CookieManager keeps all accepted cookies in memory. It will forget these cookies when the VM exits. Implement Java.Net.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);
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.
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.
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.