Android: How to store cookies?

前端 未结 5 846
挽巷
挽巷 2020-12-02 10:06

In my Android app, each activity is filled with data from an xml file which is somewhere on the web. The website providing these files has a login mechanism, that works with

相关标签:
5条回答
  • 2020-12-02 10:42

    After you make your http call, you can grab the cookies like this

    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
       Log.d(TAG,"no cookies received");
    } else {
       for (int i = 0; i < cookies.size(); i++) {
          if(cookies.get(i).getName().contentEquals("PHPSESSID")) {
             PHPSESSID = cookies.get(i).getValue();
          }
       }
    }
    

    To send them back:

    nameValuePairs.add(new BasicNameValuePair("PHPSESSID",phpsessid));
    httppost.setEntity(new UrlEncodedFormEntity(aList));
    

    aList is all your nameValuePairs

    0 讨论(0)
  • 2020-12-02 10:50

    I wrote a simple class named CookieHelper and I've provided an example of how to use this class to help all users that facing the same problem : https://github.com/augustopicciani/HttpClient-save-cookies-to-file

    0 讨论(0)
  • 2020-12-02 10:51

    Use a CookieSyncManager to store your cookie value. It can persist across application starts.

    Beware of using CookieSyncManager inside of WebViewClient#shouldInterceptRequest on KitKat. It will deadlock.

    EDIT

    CookieSyncManager was deprecated in API 21:

    This class was deprecated in API level 21. The WebView now automatically syncs cookies as necessary. You no longer need to create or use the CookieSyncManager. To manually force a sync you can use the CookieManager method flush() which is a synchronous replacement for sync().

    0 讨论(0)
  • 2020-12-02 10:51

    LoopJ has a built in persistent cookie store that can be used with or without the loopj framework

    https://github.com/loopj/android-async-http/blob/master/library/src/main/java/com/loopj/android/http/PersistentCookieStore.java

    0 讨论(0)
  • 2020-12-02 10:53

    It looks like Android is using the default in memory implementation so you will need to create your own persistent cookie store.

    This Java Tutorial outlines creating your own persistent store taking advantage of the default implementation. http://download.oracle.com/javase/tutorial/networking/cookies/custom.html

    The sample has two todo's for storage (read/write) For storage I would just use SharedPreferences to store just the session cookie that you need and not persist any others.

    The sample uses a shutdown hook which is not what you want in Android. In place of run() and the hook I would just have a new public method persist() that saves what you want, though that requires that you persist() the store by hand.

    Given that you only have one or two cookies that matter you could save them in the add(...)

    0 讨论(0)
提交回复
热议问题