Skip to content

Instantly share code, notes, and snippets.

@chuehnone
Created January 3, 2018 04:34
Show Gist options
  • Save chuehnone/0f5a066049160086f4c7e3870f4cd8f2 to your computer and use it in GitHub Desktop.
Save chuehnone/0f5a066049160086f4c7e3870f4cd8f2 to your computer and use it in GitHub Desktop.
import android.os.Build;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import java.util.ArrayList;
public class CookieTool {
public static String filterCookie(String url) {
CookieManager manager = CookieManager.getInstance();
String cookie = manager.getCookie(url);
String[] cookies = cookie.split(";");
ArrayList<String> cookieKeyList = new ArrayList<>();
StringBuilder cookieSb = new StringBuilder();
for (int i = 0 ; i < cookies.length ; i++) {
String[] temp = cookies[i].split("=");
String key = temp[0].trim();
if (cookieKeyList.contains(key) || temp.length < 2) {
continue;
}
cookieKeyList.add(key);
cookieSb.append(cookies[i]).append(";");
}
return cookieSb.substring(0, cookieSb.length() - 1);
}
public static void restoreCookie(String cookie, WebView webview, String url) {
CookieManager manager = CookieManager.getInstance();
webview.clearCache(true);
webview.clearHistory();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
manager.removeAllCookies(null);
manager.flush();
} else {
CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(webview.getContext());
cookieSyncMngr.startSync();
manager.removeAllCookie();
manager.removeSessionCookie();
cookieSyncMngr.stopSync();
cookieSyncMngr.sync();
}
manager.setAcceptCookie(true);
String[] cookies = cookie.split(";");
for (int i = 0 ; i < cookies.length ; i++) {
manager.setCookie(url, cookies[i].trim());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment