Android use CookieManager to manage cookies. But there only have one method 'removeAllCookies()' to remove cookie and this removed all cookies. Now I want to remove a cookie associated with a specified url only, and other cookies don't be removed. In this situation, how can I do?
Open your browser. Android browser: Go to Menu > More > Settings or Menu > Settings > Privacy & Security. Chrome: Go to Menu > Settings > Privacy. Android browser: Tap Clear cache, Clear history, and Clear all cookie data as appropriate.
A CookieManager class's instances provide a concrete implementation of CookieHandler. It separates the storage of cookies from the policy surrounding accepting and ignoring cookies.
I made some minor changes in @summerxiaqing's answer and I checked it works. (Added https, changed empty check to TextUtils.isEmpty, passed CookieManager by argument)
public static void clearCookieByUrl(String url, CookieManager pCookieManager, CookieSyncManager pCookieSyncManager) {
Uri uri = Uri.parse(url);
String host = uri.getHost();
clearCookieByUrlInternal(url,pCookieManager,pCookieSyncManager);
clearCookieByUrlInternal("http://." + host,pCookieManager,pCookieSyncManager);
clearCookieByUrlInternal("https://." + host,pCookieManager,pCookieSyncManager);
}
private static void clearCookieByUrlInternal(String url, CookieManager pCookieManager, CookieSyncManager pCookieSyncManager) {
if (TextUtils.isEmpty(url)) {
return;
}
String cookieString = pCookieManager.getCookie(url);
Vector<String> cookie = getCookieNamesByUrl(cookieString);
if (cookie == null || cookie.isEmpty()) {
return;
}
int len = cookie.size();
for (int i = 0; i < len; i++) {
pCookieManager.setCookie(url, cookie.get(i) + "=-1");
}
pCookieSyncManager.sync();
}
private static Vector<String> getCookieNamesByUrl(String cookie) {
if (TextUtils.isEmpty(cookie)) {
return null;
}
String[] cookieField = cookie.split(";");
int len = cookieField.length;
for (int i = 0; i < len; i++) {
cookieField[i] = cookieField[i].trim();
}
Vector<String> allCookieField = new Vector<String>();
for (int i = 0; i < len; i++) {
if (TextUtils.isEmpty(cookieField[i])) {
continue;
}
if (!cookieField[i].contains("=")) {
continue;
}
String[] singleCookieField = cookieField[i].split("=");
allCookieField.add(singleCookieField[0]);
}
if (allCookieField.isEmpty()) {
return null;
}
return allCookieField;
}
Inside the Activity
mContext = getApplicationContext();
CookieManager mCookieManager = CookieManager.getInstance();
CookieSyncManager mCookieSyncManager = CookieSyncManager.createInstance(mContext);
clearCookieByUrl("http://example.com", mCookieManager, mCookieSyncManager);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With