How to make persistent Cookies with a DefaultHttpClient in Android?

前端 未结 2 1128
南旧
南旧 2020-12-17 06:10

Im using

// this is a DefaultHttpClient
List cookies = this.getCookieStore().getCookies();

Now, since Cookie does not implem

相关标签:
2条回答
  • 2020-12-17 06:42

    The Android Asynchronous Http Library supports automatic persistent cookie storage to SharedPreferences:

    http://loopj.com/android-async-http/

    Alternatively you can just extract and use the PersistentCookieStore.java and SerializableCookie.java classes if you still want to use DefaultHttpClient.

    0 讨论(0)
  • 2020-12-17 07:01

    Create your own SerializableCookie class which implements Serializable and just copy the Cookie properties during its construction. Something like this:

    public class SerializableCookie implements Serializable {
    
        private String name;
        private String path;
        private String domain;
        // ...
    
        public SerializableCookie(Cookie cookie) {
            this.name = cookie.getName();
            this.path = cookie.getPath();
            this.domain = cookie.getDomain();
            // ...
        }
    
        public String getName() {
            return name;
        }
    
        // ...
    
    }
    

    Ensure that all properties itself are also serializable. Apart from the primitives, the String class for example itself already implements Serializable, so you don't have to worry about that.

    Alternatively you can also wrap/decorate the Cookie as a transient property (so that it doesn't get serialized) and override the writeObject() and readObject() methods accordingly. Something like:

    public class SerializableCookie implements Serializable {
    
        private transient Cookie cookie;
    
        public SerializableCookie(Cookie cookie) {
            this.cookie = cookie;
        }
    
        public Cookie getCookie() {
            return cookie;
        }
    
        private void writeObject(ObjectOutputStream oos) throws IOException {
            oos.defaultWriteObject();
            oos.writeObject(cookie.getName());
            oos.writeObject(cookie.getPath());
            oos.writeObject(cookie.getDomain());
            // ...
        }
    
        private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
            ois.defaultReadObject();
            cookie = new Cookie();
            cookie.setName((String) ois.readObject());
            cookie.setPath((String) ois.readObject());
            cookie.setDomain((String) ois.readObject());
            // ...
        }
    
    }
    

    Finally use that class instead in the List.

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