如何使持久Cookie与Android的一个DefaultHttpClient? [英] How to make persistent Cookies with a DefaultHttpClient in Android?

查看:117
本文介绍了如何使持久Cookie与Android的一个DefaultHttpClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即时通讯使用

// 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 类,它的<$c$c>implements序列化 并只复制饼干的施工过程中的属性。事情是这样的:

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

    // ...

}

确保为所有属性本身也可序列化。除了原语,在字符串类,例如本身已实现Serializable ,所以你不必担心这一点。

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.

另外,您也可以包装/装饰饼干短暂属性(这样它不会序列化),并覆盖的writeObject()的readObject()方法的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());
        // ...
    }

}

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

这篇关于如何使持久Cookie与Android的一个DefaultHttpClient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆