简体   繁体   中英

retrofit 2 / okhttp3 clear cookies

I'm using retrofit and cookieJar

okBuilder.cookieJar(getCookieJar());

Everything works great, but sometimes I want to clear cookies. How can I do it in retrofit or okhttp?

In JavaNetCookieJar are only 2 public methods:

cookieJar.loadForRequest()
cookieJar.saveFromResponse();
CookieHandler cookieHandler = new CookieManager(
            new PersistentCookieStore(ctx), CookiePolicy.ACCEPT_ALL);
    // init okhttp 3 logger
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    // init OkHttpClient
    OkHttpClient httpClient = new OkHttpClient.Builder()
            .cookieJar(new JavaNetCookieJar(cookieHandler))
            .addInterceptor(logging)
            .build();

you can use cookie handler for further modifications :)

Try this one.

    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);

    JavaNetCookieJar javaNetCookieJar = new JavaNetCookieJar(cookieManager);

    OkHttpClient client = new OkHttpClient.Builder()
                                          .cookieJar(javaNetCookieJar)
                                          .build();

    cookieManager.getCookieStore().removeAll();

I might late to post an answer for this question. Still posting an answer which might help some one who are/were stuck in clearing the cookies.

If you have use use CookieManager of android.webkit.CookieManager . Here is the solution which worked for me: The kotlin version :

var cookieManager: CookieManager = CookieManager.getInstance()
    if (cookieManager.hasCookies()) {
        // cookieManager.removeAllCookie() // deprecated
        cookieManager.removeAllCookies(ValueCallback {

        })
}

Java version :

CookieManager cookieManager = CookieManager.getInstance();
    if (cookieManager.hasCookies()) {
        cookieManager.removeAllCookie();  // or
        cookieManager.removeAllCookies(new ValueCallback<Boolean>() {
            @Override
            public void onReceiveValue(Boolean aBoolean) {

            }
        });
 }

As @Kameswari has asked "How to use this cookieManager instance with okHttp client object? "-> If you want to use CookieManager with OkHttp here how I have used with Kotlin:

 init {
    var client: OkHttpClient? = null
    val builder = OkHttpClient.Builder()
    client = OkHttpClient()
    var cookieManager: CookieManager
    try {
        builder.connectTimeout(Api.ConnectionTimeout, TimeUnit.MILLISECONDS)
        builder.writeTimeout(Api.ConnectionTimeout, TimeUnit.MILLISECONDS)
        builder.readTimeout(Api.ConnectionTimeout, TimeUnit.MILLISECONDS)
    } catch (e: Exception) {
        Log.e(e.toString())
    }

    val cacheDirectory = File(this.cacheDir, "http")
    val cacheSize = 10 * 1024 * 1024
    try {
        val cache = Cache(cacheDirectory, cacheSize.toLong())
        builder.cache(cache)

        client = builder
                .cookieJar(object : CookieJar {

                    /**
                     * @param url
                     * @param cookies list of cookies get in api response
                     */
                    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
                        ApiFunction.cookieStore[url] = cookies

                        cookieManager = CookieManager.getInstance()
                        for (cookie in cookies) {
                            cookieManager.setCookie(url.toString(), cookie.toString())
                            Log.e("saveFromResponse :  Cookie url : " + url.toString() + cookie.toString())
                        }
                    }

                    /**
                     * @param url
                     * 
                     * adding cookies with request
                     */
                    override fun loadForRequest(url: HttpUrl): List<Cookie> {
                        val cookieManager = CookieManager.getInstance()
                        val cookies: ArrayList<Cookie> = ArrayList()
                        if (cookieManager.getCookie(url.toString()) != null) {
                            val splitCookies = cookieManager.getCookie(url.toString()).split("[,;]".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                            for (i in splitCookies.indices) {
                                cookies.add(Cookie.parse(url, splitCookies[i].trim { it <= ' ' })!!)
                                Log.e("loadForRequest :Cookie.add ::  " + Cookie.parse(url, splitCookies[i].trim { it <= ' ' })!!)
                            }
                        }
                        return cookies
                    }
                })
                .build()

    } catch (e: Exception) {
        e.message
        Log.e("""Exception : ${e.message}""")
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM