标签:
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:
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(); } }
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(),
For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance, orsetChunkedStreamingMode(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(); } }
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 fromgetInputStream() for compressed streams. Instead, read that stream until it is exhausted, i.e. when read() returns -1.
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(); } }
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.
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).
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.
标签:
原文地址:http://my.oschina.net/doz/blog/525732