I’m facing an issue regarding my cookies. I have implemented a frontend logic using okhttp3 and retrofit to connect to my backend. I am able to log in my users and have a response containing my cookie but once I send other request, my cookies are not part of the request and seems to be gone.
SessionCookieJar.kt
object SessionCookieJar {
private val cookieStore: MutableMap<String, List<Cookie>> = mutableMapOf()
private val cookieJar = object : CookieJar {
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
println("Saving Cookies from response for URL: $url")
cookieStore[url.host] = cookies
println("Cookies: $cookies")
}
override fun loadForRequest(url: HttpUrl): List<Cookie> {
val cookies = cookieStore[url.host] ?: emptyList()
println("Loading Cookies for request to URL: $url")
println("Cookies: $cookies")
return cookies
}
}
val okHttpClient: OkHttpClient = OkHttpClient.Builder()
.cookieJar(cookieJar)
.build()
private val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("https://7a11-222-127-105-220.ngrok-free.app") // replace with ngrok forwarding port
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiService: ApiService = retrofit.create(ApiService::class.java)
fun printCookies() {
println("Stored Cookies:")
cookieStore.forEach { (host, cookies) ->
println("Host: $host")
cookies.forEach { cookie ->
println("Cookie: ${cookie.name}=${cookie.value}")
}
}
}
}
Service - fetch request
suspend fun fetchInventory(): List<Inventory> {
return try {
println("Fetching Inventory...")
val response = SessionCookieJar.apiService.fetchInventory(
filterStock, filterStatus, filterCategory, filterTags, sortType, sortOrder
)
SessionCookieJar.printCookies()
if (response.isSuccessful) {
response.body() ?: emptyList()
} else {
println("Response unsuccessful: ${response.code()}")
emptyList()
}
} catch (e: Exception) {
println("An Error Occurred (Fetch Inventory): $e")
emptyList()
}
}