Skip to content

Instantly share code, notes, and snippets.

@spookyuser
Forked from nikhiljha/AddCookiesInterceptor.java
Last active July 16, 2017 22:27
Show Gist options
  • Save spookyuser/afe4c15cd4dae82f7d767be219c54ac4 to your computer and use it in GitHub Desktop.
Save spookyuser/afe4c15cd4dae82f7d767be219c54ac4 to your computer and use it in GitHub Desktop.
Retrofit2/OkHttp3 Cookies (Drag and Drop, One Size Fits 99%)
import android.content.SharedPreferences
import okhttp3.Interceptor
import okhttp3.Response
import org.threeten.bp.Instant
import timber.log.Timber
import java.io.IOException
import java.util.*
import javax.inject.Inject
/**
* TAKES COOKIES OUT OF STORAGE
*
* This interceptor put all the Cookies in Preferences in the Request.
* Original written by tsuharesu
* From https://gist.github.com/nikhiljha/52d45ca69a8415c6990d2a63f61184ff
*/
class AddCookiesInterceptor
@Inject constructor(val sharedPreferences: SharedPreferences) : Interceptor {
companion object {
val PREF_COOKIES = "PREF_COOKIES"
val PREF_COOKIES_TIME_CREATED = "PREF_COOKIES_TIME_CREATED"
}
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val builder = chain.request().newBuilder()
val preferences = sharedPreferences.getStringSet(PREF_COOKIES, HashSet<String>())
val timeCreated = sharedPreferences.getLong(PREF_COOKIES_TIME_CREATED, 0)
preferences.forEach {
builder.addHeader("Cookie", it)
Timber.d(it)
}
Timber.d("Cookie was added: ${Instant.ofEpochMilli(timeCreated)}")
return chain.proceed(builder.build())
}
}
import android.content.SharedPreferences
import okhttp3.Interceptor
import okhttp3.Interceptor.Chain
import okhttp3.Response
import org.threeten.bp.Instant
import java.io.IOException
import java.util.*
import javax.inject.Inject
/**
* PUTS COOKIES IN STORAGE
*
* Original written by tsuharesu
* From https://gist.github.com/nikhiljha/52d45ca69a8415c6990d2a63f61184ff
*/
class ReceivedCookiesInterceptor
@Inject constructor(val sharedPreferences: SharedPreferences) : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Chain): Response {
val originalResponse = chain.proceed(chain.request())
if (!originalResponse.headers("Set-Cookie").isEmpty()) {
val cookies = sharedPreferences.getStringSet("PREF_COOKIES", HashSet<String>())
cookies += originalResponse.headers("Set-Cookie")
sharedPreferences
.edit()
.putStringSet("PREF_COOKIES", cookies)
.putLong("PREF_COOKIES_TIME_CREATED", Instant.now().toEpochMilli())
.apply()
}
return originalResponse
}
}
@spookyuser
Copy link
Author

Here it is in kotlin (just because) also adds the time log so you can calculate if cookies have expired.

Also uses Dependency Injection, so you'll need something like the codepath module

But it's just for illustration this isn't drag and drop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment