下面列出了java.net.HttpCookie#setMaxAge ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static List<HttpCookie> toHttpCookie(String json) {
List<HttpCookie> cookieList = new ArrayList<>();
JSONArray jsonArray = JSONArray.parseArray(json);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
HttpCookie clientCookie = new HttpCookie(jsonObject.getString("name"), jsonObject.getString("value"));
clientCookie.setDomain(jsonObject.getString("domain"));
clientCookie.setPath(jsonObject.getString("path"));
clientCookie.setMaxAge(7 * 24 * 60);
cookieList.add(clientCookie);
}
return cookieList;
}
/**
* CookieStoreImpl has a strict requirement on HttpCookie.equals() to enable replacement of
* cookies with the same name.
*/
public void testCookieEquality() throws Exception {
HttpCookie baseCookie = createCookie("theme", "light", "a.com", "/");
// None of the attributes immediately below should affect equality otherwise CookieStoreImpl
// eviction will not work as intended.
HttpCookie valueCookie = createCookie("theme", "light", "a.com", "/");
valueCookie.setValue("dark");
valueCookie.setPortlist("1234");
valueCookie.setSecure(true);
valueCookie.setComment("comment");
valueCookie.setCommentURL("commentURL");
valueCookie.setDiscard(true);
valueCookie.setMaxAge(12345L);
valueCookie.setVersion(1);
assertEquals(baseCookie, valueCookie);
// Changing any of the 3 main identity attributes should render cookies unequal.
assertNotEquals(createCookie("theme2", "light", "a.com", "/"), baseCookie);
assertNotEquals(createCookie("theme", "light", "b.com", "/"), baseCookie);
assertNotEquals(createCookie("theme", "light", "a.com", "/path"), baseCookie);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
clientCookie = new HttpCookie(name, value);
clientCookie.setComment((String) in.readObject());
clientCookie.setCommentURL((String) in.readObject());
clientCookie.setDomain((String) in.readObject());
clientCookie.setPath((String) in.readObject());
clientCookie.setMaxAge(in.readLong());
clientCookie.setVersion(in.readInt());
clientCookie.setSecure(in.readBoolean());
clientCookie.setDiscard(in.readBoolean());
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
cookie = new HttpCookie(name, value);
cookie.setComment((String) in.readObject());
cookie.setCommentURL((String) in.readObject());
cookie.setDomain((String) in.readObject());
cookie.setMaxAge(in.readLong());
cookie.setPath((String) in.readObject());
cookie.setPortlist((String) in.readObject());
cookie.setVersion(in.readInt());
cookie.setSecure(in.readBoolean());
cookie.setDiscard(in.readBoolean());
setHttpOnly(in.readBoolean());
}
public static void updateCookies(Context context) {
SimpleCookieStore cookieStore = NMBApplication.getSimpleCookieStore(context);
URL url = ACSite.getInstance().getSiteUrl();
HttpCookieWithId hcwi = cookieStore.getCookie(url, "userId");
if (hcwi != null) {
HttpCookie oldCookie = hcwi.httpCookie;
cookieStore.remove(url, oldCookie);
HttpCookie newCookie = new HttpCookie("userhash", oldCookie.getValue());
newCookie.setComment(oldCookie.getComment());
newCookie.setCommentURL(oldCookie.getCommentURL());
newCookie.setDiscard(oldCookie.getDiscard());
newCookie.setDomain(oldCookie.getDomain());
newCookie.setMaxAge(oldCookie.getMaxAge());
newCookie.setPath(oldCookie.getPath());
newCookie.setPortlist(oldCookie.getPortlist());
newCookie.setSecure(oldCookie.getSecure());
newCookie.setVersion(oldCookie.getVersion());
cookieStore.add(url, newCookie);
}
}
@Nullable
public HttpCookie to() {
if (name == null || value == null) {
return null;
}
HttpCookie cookie = new HttpCookie(name, value);
cookie.setComment(comment);
cookie.setCommentURL(commentURL);
cookie.setDiscard(discard);
cookie.setDomain(domain);
cookie.setMaxAge(maxAge);
cookie.setPath(path);
cookie.setPortlist(portList);
cookie.setSecure(secure);
cookie.setVersion(version);
return cookie;
}
private void processCookieText(String text) {
try {
JSONObject jo = new JSONObject(text);
String userhash = jo.getString("cookie");
if (userhash == null) {
throw new NullPointerException("cookie is null");
}
HttpCookie cookie = new HttpCookie("userhash", userhash);
cookie.setDomain(ACUrl.DOMAIN);
cookie.setPath("/");
cookie.setMaxAge(-1);
SimpleCookieStore store = NMBApplication.getSimpleCookieStore(this);
store.add(new URL(ACUrl.getHost()), cookie);
Toast.makeText(this, R.string.qr_scan_succeed, Toast.LENGTH_SHORT).show();
finish();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, R.string.qr_scan_invalid, Toast.LENGTH_SHORT).show();
}
}
public static List<HttpCookie> getCookieList(ByteBuffer buffer) {
int len = buffer.getChar();
if (len == 0) return null;
final List<HttpCookie> list = new ArrayList<>(len);
for (int i = 0; i < len; i++) {
HttpCookie cookie = new HttpCookie(getShortString(buffer), getShortString(buffer));
cookie.setDomain(getShortString(buffer));
cookie.setPath(getShortString(buffer));
cookie.setPortlist(getShortString(buffer));
cookie.setMaxAge(buffer.getLong());
cookie.setSecure(buffer.get() == 1);
cookie.setHttpOnly(buffer.get() == 1);
list.add(cookie);
}
return list;
}
/**
* Into {@link HttpCookie}.
*
* @return {@link HttpCookie}.
*/
public HttpCookie toHttpCookie() {
HttpCookie cookie = new HttpCookie(name, value);
cookie.setComment(comment);
cookie.setCommentURL(commentURL);
cookie.setDiscard(discard);
cookie.setDomain(domain);
if (expiry == -1L)
cookie.setMaxAge(-1L);
else
cookie.setMaxAge((expiry - System.currentTimeMillis()) / 1000L);
cookie.setPath(path);
cookie.setPortlist(portList);
cookie.setSecure(secure);
cookie.setVersion(version);
return cookie;
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
cookie = new HttpCookie(name, value);
cookie.setComment((String) in.readObject());
cookie.setCommentURL((String) in.readObject());
cookie.setDomain((String) in.readObject());
cookie.setMaxAge(in.readLong());
cookie.setPath((String) in.readObject());
cookie.setPortlist((String) in.readObject());
cookie.setVersion(in.readInt());
cookie.setSecure(in.readBoolean());
cookie.setDiscard(in.readBoolean());
setHttpOnly(in.readBoolean());
}
/**
* 用户登陆
*
* @param req
* @param resp
*
* @throws IOException
*/
@HttpMapping(url = "/user/login", auth = false)
public void login(HttpRequest req, HttpResponse resp) throws IOException {
LoginBean bean = req.getJsonParameter(LoginBean.class, "bean");
if (bean == null) bean = new LoginBean();
if (!bean.emptyPassword()) bean.setPassword(UserService.secondPasswordMD5(bean.getPassword()));
bean.setLoginagent(req.getHeader("User-Agent"));
bean.setLoginip(req.getRemoteAddr());
String oldsessionid = req.getSessionid(false);
if (oldsessionid != null && !oldsessionid.isEmpty()) service.logout(oldsessionid);
bean.setSessionid(req.changeSessionid());
RetResult<UserInfo> result = service.login(bean);
if (result.isSuccess() && !bean.emptyPassword()) { //必须是密码登录类
if (bean.getCacheday() > 0 && bean.emptyCookieinfo()) { //保存N天
UserInfo info = result.getResult();
int age = bean.getCacheday() * 24 * 60 * 60;
String key = (bean.emptyApptoken() ? "" : (bean.getApptoken() + "#")) + info.getUser36id() + "$0" + bean.getPassword() + "?" + age + "-" + System.currentTimeMillis();
HttpCookie cookie = new HttpCookie(COOKIE_AUTOLOGIN, UserService.encryptAES(key));
cookie.setHttpOnly(true);
cookie.setPath("/");
cookie.setMaxAge(age);
resp.addCookie(cookie);
}
}
resp.finishJson(result);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
clientCookie = new HttpCookie(name, value);
clientCookie.setComment((String) in.readObject());
clientCookie.setCommentURL((String) in.readObject());
clientCookie.setDomain((String) in.readObject());
clientCookie.setMaxAge(in.readLong());
clientCookie.setPath((String) in.readObject());
clientCookie.setPortlist((String) in.readObject());
clientCookie.setVersion(in.readInt());
clientCookie.setSecure(in.readBoolean());
clientCookie.setDiscard(in.readBoolean());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
cookie = new HttpCookie(name, value);
cookie.setComment((String) in.readObject());
cookie.setCommentURL((String) in.readObject());
cookie.setDomain((String) in.readObject());
cookie.setMaxAge(in.readLong());
cookie.setPath((String) in.readObject());
cookie.setPortlist((String) in.readObject());
cookie.setVersion(in.readInt());
cookie.setSecure(in.readBoolean());
cookie.setDiscard(in.readBoolean());
// setHttpOnly(in.readBoolean());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
String name = (String) in.readObject();
String value = (String) in.readObject();
clientCookie = new HttpCookie(name, value);
clientCookie.setComment((String) in.readObject());
clientCookie.setCommentURL((String) in.readObject());
clientCookie.setDomain((String) in.readObject());
clientCookie.setMaxAge(in.readLong());
clientCookie.setPath((String) in.readObject());
clientCookie.setPortlist((String) in.readObject());
clientCookie.setVersion(in.readInt());
clientCookie.setSecure(in.readBoolean());
clientCookie.setDiscard(in.readBoolean());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
clientCookie = new HttpCookie(name, value);
clientCookie.setComment((String) in.readObject());
clientCookie.setCommentURL((String) in.readObject());
clientCookie.setDomain((String) in.readObject());
clientCookie.setMaxAge(in.readLong());
clientCookie.setPath((String) in.readObject());
clientCookie.setPortlist((String) in.readObject());
clientCookie.setVersion(in.readInt());
clientCookie.setSecure(in.readBoolean());
clientCookie.setDiscard(in.readBoolean());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
cookie = new HttpCookie(name, value);
cookie.setComment((String) in.readObject());
cookie.setCommentURL((String) in.readObject());
cookie.setDomain((String) in.readObject());
cookie.setMaxAge(in.readLong());
cookie.setPath((String) in.readObject());
cookie.setPortlist((String) in.readObject());
cookie.setVersion(in.readInt());
cookie.setSecure(in.readBoolean());
cookie.setDiscard(in.readBoolean());
setHttpOnly(in.readBoolean());
}
private HttpCookie cookie2HttpCookie(Cookie cookie) {
HttpCookie httpCookie = new HttpCookie(cookie.name(), cookie.value());
if (cookie.expiresAt() < System.currentTimeMillis()) {
httpCookie.setMaxAge(-100L);
} else {
httpCookie.setMaxAge((cookie.expiresAt() - System.currentTimeMillis()) / 1000);
}
httpCookie.setDomain(cookie.domain());
httpCookie.setPath(cookie.path());
httpCookie.setSecure(cookie.secure());
return httpCookie;
}
/**
* 修改密码
*
* @param req
* @param resp
*
* @throws IOException
*/
@HttpMapping(url = "/user/updatepwd")
public void updatepwd(HttpRequest req, HttpResponse resp) throws IOException {
UserPwdBean bean = req.getJsonParameter(UserPwdBean.class, "bean");
UserInfo curr = req.currentUser();
if (curr != null) bean.setSessionid(req.getSessionid(false));
RetResult<UserInfo> result = service.updatePwd(bean);
if (result.isSuccess() && curr == null) { //找回的密码
curr = result.getResult();
LoginBean loginbean = new LoginBean();
loginbean.setAccount(curr.getEmail().isEmpty() ? curr.getMobile() : curr.getEmail());
loginbean.setPassword(UserService.secondPasswordMD5(bean.getNewpwd()));
loginbean.setSessionid(req.changeSessionid());
loginbean.setLoginagent(req.getHeader("User-Agent"));
loginbean.setLoginip(req.getRemoteAddr());
result = service.login(loginbean);
}
String autologin = req.getCookie(COOKIE_AUTOLOGIN);
if (result.isSuccess() && autologin != null) {
autologin = UserService.decryptAES(autologin);
if (autologin.contains("$0")) { //表示COOKIE_AUTOLOGIN 为密码类型存储
String newpwd = UserService.secondPasswordMD5(bean.getNewpwd());
int wen = autologin.indexOf('?');
int mei = autologin.indexOf('$');
String key = autologin.substring(0, mei + 2) + newpwd + autologin.substring(wen);
HttpCookie cookie = new HttpCookie(COOKIE_AUTOLOGIN, UserService.encryptAES(key));
cookie.setHttpOnly(true);
cookie.setPath("/");
String time = autologin.substring(wen + 1);
int fen = time.indexOf('-');
int age = Integer.parseInt(time.substring(0, fen)); //秒数
long point = Long.parseLong(time.substring(fen + 1)); //毫秒数
cookie.setMaxAge(age - (System.currentTimeMillis() - point) / 1000);
resp.addCookie(cookie);
}
}
resp.finishJson(result);
}
@HttpMapping(url = "/user/logout", auth = false)
public void logout(HttpRequest req, HttpResponse resp) throws IOException {
String sessionid = req.getSessionid(false);
if (sessionid != null) service.logout(sessionid);
HttpCookie cookie = new HttpCookie(COOKIE_AUTOLOGIN, "");
cookie.setPath("/");
cookie.setMaxAge(1);
resp.addCookie(cookie);
resp.finish("{\"success\":true}");
}
/**
* java.net.CookieStore#remove(URI, HttpCookie)
* @since 1.6
*/
public void test_remove_LURI_LHttpCookie() throws URISyntaxException {
URI uri1 = new URI("http://remove1.test.com");
HttpCookie cookie1 = new HttpCookie("cookie_name1", "cookie_value1");
try {
cookieStore.remove(uri1, null);
fail("should throw NullPointerException");
} catch (NullPointerException e) {
// expected
}
assertFalse(cookieStore.remove(uri1, cookie1));
assertFalse(cookieStore.remove(null, cookie1));
cookieStore.add(uri1, cookie1);
URI uri2 = new URI("http://remove2.test.com");
HttpCookie cookie2 = new HttpCookie("cookie_name2", "cookie_value2");
cookieStore.add(uri2, cookie2);
assertTrue(cookieStore.remove(uri1, cookie1));
assertFalse(cookieStore.remove(uri1, cookie1));
assertEquals(2, cookieStore.getURIs().size());
assertEquals(1, cookieStore.getCookies().size());
assertTrue(cookieStore.remove(uri2, cookie2));
assertFalse(cookieStore.remove(uri2, cookie2));
assertEquals(2, cookieStore.getURIs().size());
assertEquals(0, cookieStore.getCookies().size());
assertTrue(cookieStore.removeAll());
cookieStore.add(uri1, cookie1);
cookieStore.add(uri2, cookie2);
HttpCookie cookie3 = new HttpCookie("cookie_name3", "cookie_value3");
assertFalse(cookieStore.remove(null, cookie3));
// No guarantees on behavior if we call remove with a different
// uri from the one originally associated with the cookie.
assertFalse(cookieStore.remove(null, cookie1));
assertTrue(cookieStore.remove(uri1, cookie1));
assertFalse(cookieStore.remove(uri1, cookie1));
assertEquals(2, cookieStore.getURIs().size());
assertEquals(1, cookieStore.getCookies().size());
assertTrue(cookieStore.remove(uri2, cookie2));
assertFalse(cookieStore.remove(uri2, cookie2));
assertEquals(2, cookieStore.getURIs().size());
assertEquals(0, cookieStore.getCookies().size());
cookieStore.removeAll();
// expired cookies can also be deleted.
cookie2.setMaxAge(-34857);
cookieStore.add(uri2, cookie2);
assertTrue(cookieStore.remove(uri2, cookie2));
assertFalse(cookieStore.remove(uri2, cookie2));
assertEquals(0, cookieStore.getCookies().size());
cookie2.setMaxAge(34857);
cookieStore.add(uri1, cookie1);
cookieStore.add(uri2, cookie1);
cookieStore.add(uri2, cookie2);
assertTrue(cookieStore.remove(uri1, cookie1));
assertFalse(cookieStore.remove(uri1, cookie1));
assertTrue(cookieStore.get(uri2).contains(cookie1));
assertTrue(cookieStore.get(uri2).contains(cookie2));
assertEquals(0, cookieStore.get(uri1).size());
cookieStore.remove(uri2, cookie2);
cookieStore.removeAll();
cookieStore.add(uri2, cookie2);
cookieStore.add(uri1, cookie1);
assertEquals(2, cookieStore.getCookies().size());
assertFalse(cookieStore.remove(uri2, cookie1));
assertTrue(cookieStore.remove(uri1, cookie1));
assertEquals(2, cookieStore.getURIs().size());
assertEquals(1, cookieStore.getCookies().size());
assertTrue(cookieStore.getCookies().contains(cookie2));
cookieStore.removeAll();
URI uri3 = new URI("http://remove3.test.com");
URI uri4 = new URI("http://test.com");
HttpCookie cookie4 = new HttpCookie("cookie_name4", "cookie_value4");
cookie4.setDomain(".test.com");
cookie2.setMaxAge(-34857);
cookie3.setMaxAge(-22);
cookie4.setMaxAge(-45);
cookieStore.add(uri1, cookie1);
cookieStore.add(uri2, cookie2);
cookieStore.add(uri3, cookie3);
cookieStore.add(uri4, cookie4);
assertEquals(0, cookieStore.get(uri2).size());
assertFalse(cookieStore.remove(uri2, cookie2));
assertTrue(cookieStore.remove(uri3, cookie3));
assertFalse(cookieStore.remove(uri4, cookie4));
}