Skip to content

Instantly share code, notes, and snippets.

@mochico
Last active August 29, 2016 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mochico/c1acf4ca0d5caf76d29fd12d239053f3 to your computer and use it in GitHub Desktop.
Save mochico/c1acf4ca0d5caf76d29fd12d239053f3 to your computer and use it in GitHub Desktop.
import com.squareup.okhttp.Response;
import com.squareup.okhttp.internal.http.HttpDate;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
/**
* NでOpenJDKへの変更によりCookieManagerのexpiresのparse方法が変わってしまいcookiejarに追加されていないCookieがあるので、
* ResponseからCookieを取り出しCookieManagerに追加します
*/
public class CookieUpdater {
public static void updateCookies(Response response, CookieManager cookieManager) {
List<String> cookies = response.headers("Set-Cookie");
for (String cookieString : cookies) {
StringTokenizer stringTokenizer = new StringTokenizer(cookieString, ";");
stringTokenizer.nextToken(); // 最初のtokenはCookieのname/valueなので次に進める
List<java.net.HttpCookie> httpCookies = java.net.HttpCookie.parse(cookieString);
for (HttpCookie httpCookie : httpCookies) {
if (httpCookie.getMaxAge() == 0) {
// Dateのパースに失敗している可能性があるのでmaxAgeをセットしなおす
while (stringTokenizer.hasMoreTokens()) {
String token = stringTokenizer.nextToken();
if (!token.contains("expires")) {
continue;
}
String expiresValue = token.substring(token.indexOf('=') + 1);
expiresValue = expiresValue.replace("\"", "").trim();
Date date = HttpDate.parse(expiresValue);
httpCookie.setMaxAge(date != null ? (date.getTime() - System.currentTimeMillis()) / 1000 : -1); // 0がセットされるとNでcookiejarに追加されないので-1をセットする
break;
}
}
try {
cookieManager.getCookieStore()
.add(new URI("https", "any.your.domain", null, null), httpCookie);
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment