如何使持久Cookie与Android的一个DefaultHttpClient?持久、Cookie、DefaultHttpClient、Android

2023-09-04 23:47:33 作者:慌言☆的☆世界

即时通讯使用

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

现在,因为饼干没有实现可序列化,我不能序列化列表。

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

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

(specified my goal, not only the problem)

我的目标是使用具有持久Cookie的DefaultHttpClient。

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...

推荐答案

创建自己的 SerializableCookie 类,它的accordingly 。是这样的:

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

}

最后使用类,而不是在列表

 
精彩推荐
图片推荐