How do I make persistent cookies using DefaultHttpClient in Android?
I’m using
// this is a DefaultHttpClient
List<Cookie> cookies = this.getCookieStore().getCookies();
Now, since cookies are not implemented serializable, I can’t serialize the list.
EDIT: (Specify my goal, not just a question).
My goal is to use DefaultHttpClient with persistent cookies.
Can someone with experience guide me down the right path? There may be another best practice that I haven’t found….
Solution
Create your own SerializableCookie
class > implements serializable and copies the cookie attribute during the
build process. 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 are also serializable themselves. In addition to primitives, such as the String
class itself already implements Serializable
, so you don’t have to worry about that.
Alternatively, you can wrap/decorate the cookie
as a transient
property (so it is not serialized) and override the writeObject() and readObject(
)
methods
accordingly
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 the class in List
.