okHttp3.0+ Cookies持久化

2016-08-10  本文已影响0人  十月未央

SerializableOkHttpCookies

主要做两件事:

将Cookie对象输出为ObjectStream

将ObjectStream序列化成Cookie对象

public class SerializableOkHttpCookies implements Serializable {

private transient final Cookie cookies;

private transient Cookie clientCookies;

public SerializableOkHttpCookies(Cookie cookies) {

this.cookies = cookies;

}

public Cookie getCookies() {

Cookie bestCookies = cookies;

if (clientCookies != null) {

bestCookies = clientCookies;

}

return bestCookies;

}

private void writeObject(ObjectOutputStream out) throws IOException {

out.writeObject(cookies.name());

out.writeObject(cookies.value());

out.writeLong(cookies.expiresAt());

out.writeObject(cookies.domain());

out.writeObject(cookies.path());

out.writeBoolean(cookies.secure());

out.writeBoolean(cookies.httpOnly());

out.writeBoolean(cookies.hostOnly());

out.writeBoolean(cookies.persistent());

}

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {

String name = (String) in.readObject();

String value = (String) in.readObject();

long expiresAt = in.readLong();

String domain = (String) in.readObject();

String path = (String) in.readObject();

boolean secure = in.readBoolean();

boolean httpOnly = in.readBoolean();

boolean hostOnly = in.readBoolean();

boolean persistent = in.readBoolean();

Cookie.Builder builder = new Cookie.Builder();

builder = builder.name(name);

builder = builder.value(value);

builder = builder.expiresAt(expiresAt);

builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain);

builder = builder.path(path);

builder = secure ? builder.secure() : builder;

builder = httpOnly ? builder.httpOnly() : builder;

clientCookies =builder.build();

}

}

上一篇下一篇

猜你喜欢

热点阅读