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 D开发者_如何转开发efaultHttpClient 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...
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
.
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.
精彩评论