How to make persistent Cookies with a DefaultHttpC

2019-01-24 19:18发布

问题:

Im using

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

Now, since Cookie does not implement serializeable, I can't serialize that List.

EDIT: (specified my goal, not only the problem)

My goal is to use the DefaultHttpClient with persistent cookies.

Anyone with experience that could lead me on the right track here? There might be another best practice that I haven't discovered...

回答1:

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.



回答2:

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.