如何在Android中使用DefaultHttpClient创建持久性Cookie?

Vid*_*nes 3 java android http

我正在使用

// this is a DefaultHttpClient
List<Cookie> cookies = this.getCookieStore().getCookies();
Run Code Online (Sandbox Code Playgroud)

现在,由于Cookie没有实现序列化,我无法序列化该List.

编辑:(指定我的目标,不仅是问题)

我的目标是将DefaultHttpClient与持久性cookie一起使用.

有经验的人可以带领我走上正轨吗?可能还有另一种我没有发现的最佳实践......

Bal*_*usC 6

创建自己的SerializableCookie类,implements SerializableCookie在构造过程中复制属性.像这样的东西:

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;
    }

    // ...

}
Run Code Online (Sandbox Code Playgroud)

确保所有属性本身也可序列化.除了原语之外,这个String类本身已经存在implements Serializable,所以你不必担心这一点.

另外,您也可以包装/装饰Cookie作为一个transient属性(这样没有被序列化),并覆盖writeObject()readObject()方法相应.就像是:

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());
        // ...
    }

}
Run Code Online (Sandbox Code Playgroud)

最后使用该类代替List.