Android Official API Translator--httpurlconnection

Source: Internet
Author: User
Tags http authentication

Manual translation, limited level, welcome to communicate

Original address:


Inherit from

URLConnection for HTTP (RFC 2616) for sending and receiving data over the network. This class can be used to send or receive streaming data that does not know the length beforehand.

You can use this class in the following ways:

1. Get the HttpURLConnection instance by calling the Url.openconnection () method and then performing a forced type conversion.

2. Prepare the request. The main component of a network request is a URI, and the request header may also contain data such as credentials, preferred content type, Session cookies, and so on.

3. The request body is an optional upload content, a HttpURLConnection object to carry the request body must be set Setdooutput (true). Transmits data by writing to the stream returned by Getoutputstream ().

4. Read the response. The head of the response data usually contains metadata such as data content type, length, date modified, and session cookies. The response data can be read by the stream returned by getInputStream (). If there is no response data, this method returns an empty stream.

5. Disconnect the connection. Once the returned data has been read, the httpurlconnection should be closed by calling disconnect (). Disconnecting frees the resources used by the connection so that the resources are shut down or recycled.

For example, get's web page data code as follows:

1URL url =NewURL ("");2HttpURLConnection URLConnection =(HttpURLConnection) url.openconnection ();3    Try {4InputStream in =NewBufferedinputstream (Urlconnection.getinputstream ());5 Readstream (in);6     finally {7 Urlconnection.disconnect ();8    }9}

HTTPS Secure Communication

When calling OpenConnection (), if the URL prefix is HTTPS, you can obtain an httpsurlconnection instance, overriding the default Hostnameverifier and Sslsocketfactory. An application-supplied sslsocketfactory created from Sslconext can provide a custom X509trustmanager for validating the certificate chain and a custom X509keymanager to provide a terminal certificate. Details are described in httpsurlconnection.

Handling Responses

HttpURLConnection supports up to five HTTP redirects and can follow redirects from one original server to another. However, redirects from HTTPS to HTTP are not supported, and vice versa.

If an HTTP response shows an error, getInputStream () throws a IOException exception. The error message can be read by Geterrorstream (). Head data can usually be read by Getheaderfields ().

Send data

To upload data to a Web server, you need to set connection to output using Setdooutput (true).

In order to achieve the best performance, you should:

Set Setfixedlengthstreamingmode (int) If the data length is known

Set Setchunkstramingmode (int) If the data length is unknown

Otherwise, httpurlconnection forces the entire request body to be cached in memory before the data is transferred, wasting (or potentially exhausting) heap space and increasing latency.

The sample code for uploading data is as follows:

1HttpURLConnection URLConnection =(HttpURLConnection) url.openconnection ();2    Try {3Urlconnection.setdooutput (true);4Urlconnection.setchunkedstreamingmode (0);5 6OutputStream out =NewBufferedoutputstream (Urlconnection.getoutputstream ());7 Writestream (out);8 9InputStream in =NewBufferedinputstream (Urlconnection.getinputstream ());Ten Readstream (in); One     finally { A Urlconnection.disconnect (); -    } -}


The input and output streams obtained through this class are not cached . Most calls should be Bufferedinputstream or bufferedoutputstream to encapsulate the original stream that is returned. A call to a bulk read or write or an ignorable cache.

When there is large data transfer to the server, you should use a stream to limit the amount of data in memory at the same time. Unless you need to store all your data in memory at once, treat it as a whole stream (instead of sorting the data as a byte or string array).

To reduce latency, the httpurlconnection can use the same underlying socket when dealing with multiple requests/responses. As a result, the HTTP connection may be turned on longer than needed. Calling disconnect () may return the socket to a pool that has a connected socket. To avoid this behavior, you can set the system property http.keepalive to False before any HTTP requests are made. Http.maxconnections can be used to control how many idle connections are maintained for each server.

By default, this implementation of httpurlconnection requires that the server use gzip compression. So, although Getcontentlength () can return the number of bits transferred, you should not rely on this method to estimate the number of bytes that can be obtained from getInputStream (). Instead, you should always read the data from the stream until it is read, that is, when read () returns-1 o'clock. Gzip compression can be set at the request header's accept encoding to disable:

1 urlconnection.setrequestproperty ("Accept-encoding", "identity");

Processing Network Logins

Some Wi-Fi networks require users to log in to provide normal service. This type of login page is typically implemented through HTTP redirection. You can use Geturl () to test whether your connection is being redirected unexpectedly. This method is not valid until the requested header data is received, and you can trigger the operation of the header data being received by Getheaderfields () or getInputStream ().

Here is the code that detects whether a request is redirected to another host:

1HttpURLConnection URLConnection =(HttpURLConnection) url.openconnection ();2    Try {3InputStream in =NewBufferedinputstream (Urlconnection.getinputstream ());4      if(!url.gethost (). Equals (Urlconnection.geturl (). GetHost ())) {5        //we were redirected! Kick the "user out" to the browser?6      7      ...8}finally {9 Urlconnection.disconnect ();Ten    } One}

HTTP Authentication

HttpURLConnection supports HTTP Basic authentication. Use authenticator to set up a VM-level authentication Processor:

   Authenticator.setdefault (new  Authenticator () {     protected  Passwordauthentication getpasswordauthentication () {       returnnew  Passwordauthentication (username, Password.tochararray ());        }); }

This is not a secure user authentication mechanism unless used in conjunction with HTTPS. It is important to note that user names, passwords, request data, and response data transmitted over the network are unencrypted.

-Not to be continued

Android Official API Translator--httpurlconnection

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.