我正在使用
// this is a DefaultHttpClient
List<Cookie> cookies = this.getCookieStore().getCookies();
现在,由于Cookie没有实现可序列化接口,我无法序列化该List。
编辑:(明确了我的目标,不仅是问题)
我的目标是使用DefaultHttpClient和持久性Cookie。
有经验的人能否指导我正确的方向?可能还有其他最佳实践我还未发现...
SerializableCookie
类,它实现了Serializable
接口,在构造时只需复制Cookie
属性即可。代码如下: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;
}
// ...
}
确保所有属性本身也可序列化。除了原始类型,例如 String
类已经实现了 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());
// ...
}
}
List
中使用那个类。
Map
中,并代之以序列化。 - BalusC