Android Network Programming --- HttpClient and HttpURLConnection share cookies

Source: Internet
Author: User
Tags send cookies

HttpClient and HttpURLConnection share SessionId

HttpClient and HttpUrlConnection are the most common HTTP access methods in Android. These two methods are sometimes used in an application. How can they share cookies and allow the client to access the server to maintain Session communication.

HttpClient and HttpUrlConnection are used to obtain and send cookies, mainly sharing sessionID.

HttpClient:

HttpPost httpPost = new HttpPost (url); // send the SessionId to the server if (null! = MSESSIONID) {httpPost. setHeader ("Cookie", "SESSIONID =" + mSESSIONID);} DefaultHttpClient httpClient = new DefaultHttpClient (); httpResponse = httpClient.exe cute (httpPost); if (httpResponse. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {HttpEntity entity = httpResponse. getEntity (); CookieStore mCookieStore = httpClient. getCookieStore (); List
 
  
Cookies = mCookieStore. getCookies (); // read the value of the specified Cookie for (int I = 0; I <cookies. size (); I ++) {if ("SESSIONID ". equals (cookies. get (I ). getName () {mSESSIONID = cookies. get (I ). getValue (); break ;}}}
 

Save the above sessionId in the program, or use global variables or SharedPreferences to view the session time and program business of this sessionId.

HttpUrlConnection:
HttpURLConnection url_con = null; URL url = new URL (reqUrl); url_con = (HttpURLConnection) url. openConnection (); // set session if (mSESSIONID! = Null) {url_con.setRequestProperty ("Cookie", "JSESSIONID =" + mSESSIONID );}... string cookieVal = con. getHeaderField ("Set-Cookie"); // obtain the session if (cookieVal! = Null) {StringmSESSIONID = cookieVal. substring (0, cookieVal. indexOf (";"));}


Comparison between HttpURLConnection and HttpClient (Android ):
Both HttpURLConnection and HttpClient support HTTPS protocol, IPv6, stream upload and download, configuration timeout, and connection pool. DefaultHttpClient and its brother AndroidHttpClient are both specific implementation classes of HttpClient. They all have a large number of APIS, and their implementations are relatively stable and there are few bugs. However, due to the large number of HttpClient APIs, it is difficult for us to upgrade and expand HttpClient without compromising its compatibility, therefore, the Android team is not active in improving and optimizing HttpClient.


HttpURLConnection is a multi-purpose, lightweight HTTP client that can be used for HTTP operations in most applications. Although the HttpURLConnection API is relatively simple, it also makes it easier for us to use and expand it. However, before Android 2.2, HttpURLConnection had some annoying bugs. For example, when you call the close () method for a readable InputStream, the connection pool may become invalid. The common solution is to disable the connection pool function directly:

Some HTTPS improvements have been added in Android 2.3. Now, HttpsURLConnection uses the SNI (Server Name Indication) method to connect, so that multiple HTTPS hosts can share the same IP address. In addition, some compression and session mechanisms are added. If the connection fails, it will automatically try again. This allows HttpsURLConnection to connect to the latest server more efficiently without compromising the compatibility of earlier versions.


In Android 4.0, we added some response caching mechanisms. After the cache is installed (call the install () method of HttpResponseCache), all HTTP requests will meet the following three conditions:

1. All cache responses are provided by local storage. Because there is no need to initiate a network connection request for a task, all responses can be obtained immediately.
2. Depending on the situation, the cache response must have a server for update check. For example, if the client initiates a request like "if the image/foo.png has changed, send it to me", and the server needs to return the updated data, or a 304 Not Modified status is returned. If the requested content does not occur, the client will not download any data.
3. responses without caching are directly provided by the server. These responses will be stored in the response cache later.


Because this function is available only in Versions later than 4.0, we can usually use reflection to start the response cache function. The following sample code shows how to enable the response cache function in Android 4.0 and later versions without affecting previous versions:
private void enableHttpResponseCache() {      try {          long httpCacheSize = 10 * 1024 * 1024; // 10 MiB          File httpCacheDir = new File(getCacheDir(), "http");          Class.forName("android.net.http.HttpResponseCache")              .getMethod("install", File.class, long.class)              .invoke(null, httpCacheDir, httpCacheSize);      } catch (Exception httpResponseCacheNotAvailable) {      }  }  
You should also configure your Web server and add the cached message header to the HTTP response.
Which one is the best?
Before Android 2.2, HttpClient had fewer bugs, so using it is the best choice.
In Android 2.3 and later versions, HttpURLConnection is the best choice. Its API is simple and small, so it is very suitable for Android projects. The compression and cache mechanisms can effectively reduce network access traffic and play a major role in improving speed and saving power. New applications should be more inclined to use 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: info-contact@alibabacloud.com 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.