Android local storage Cookie (for HttpClient)
Recently, someone asked me how to save the HttpClient Cookie, so I will write it down here. By the way, let's record it. Of course, kids shoes who have Android network programming experience can understand it at a glance ~
Let's just move on to the Code:
/*** Local storage Cookie * @ param response */private void saveCookies (HttpResponse response) {SharedPreferences preferences = getSharedPreferences (cookies, MODE_PRIVATE); List
TheCookies = client. getCookieStore (). getCookies (); StringBuffer sb = new StringBuffer (); for (int k = 0; k
Set Cookie:
String url = http://www.host.com/test; HttpGet get = new HttpGet (url); SharedPreferences sharedPreferences = getSharedPreferences (cookies, MODE_PRIVATE); get. setHeader (Cookie, sharedPreferences. getString (cookies,); try {HttpResponse response = client.exe cute (get); HttpEntity entity = response. getEntity (); if (response. getStatusLine (). getStatusCode ()! = HttpStatus. SC _ OK) {Log. e (TAG, failed to save );//...} else {Log. e (TAG, saved successfully );//...}} catch (Exception e) {e. printStackTrace ();}
In this way, you can avoid repeated HTTp requests, such as repeated logon. however, you must note that the Cookie is valid. If it is used after the validity period expires, it will be invalid. You must log on again to perform other operations. in the code above, the Cookie validity period is one month.
Therefore, when using cookies, you can save the Cookie's validity period at the same time. Of course, if you do not save the Cookie, the server will naturally return the corresponding prompt to access it with an invalid Cookie. Then, you can respond as prompted. in addition, Cookie is a simple text data that records access information between the server and the client. Therefore, it is highly efficient to read, store, and manage data, but it is not secure enough, it is best to pay attention to security for local storage. of course, if it is not very important data and has good usage habits, there is nothing.
The above is the original HttpClient for Android development environment, if it is to use other Apache HttpClient jar package, such as commons-httpclient-3.1.jar. it may be found that the above method is not convenient to use, so we can also imitate the browser's Cookie processing policy, using the unique httpPost in the jar package. setRequestHeader () method to add access information, such
HttpPost. setRequestHeader (Host, host address );
HttpPost. setRequestHeader (Connection, Keep-Alive );
HttpPost. setRequestHeader (Cookie, cookie );
HttpPost. setRequestHeader (User-Agent, userAgent );
Then, we can use the packet capture tool to view a request from a computer browser. We can see the Cookie data in a similar format in Headers (a request to access a website in youdao ):
It can be seen that this processing method is similar to the browser policy.