Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ktor force refresh cache-control endpoint

I've started using Ktor (recently updated to 2.0.0) on a new android project, to consume an API endpoint configured to have the Cache-Control: max-age=3600 header on their responses.

I've set up my client as specified on Ktor's docs:

val client = HttpClient(CIO) {
    install(HttpCache)
}

In the app I need to implement a refresh feature which will force a request to ignore Cache-Control and request fresh data.

How this is possible using ktor?

To get the resources I'm using

private suspend fun HttpClient.getRemote(): List<Foo> = get("https://www.example.com/api_endpoint").body()

and I assume that I need to specify something in the get(...)'s body implementation, but I don't know what.

like image 741
Valerio Avatar asked Dec 13 '25 19:12

Valerio


1 Answers

You can add refreshData parameter to your API function which defaults to false (to enable caching), and whenever you want fresh data, just pass true, and the current time in milliseconds will be appended as a query to the URL.

    suspend fun getDataFromSpreadsheet(
        spreadsheetId: String,
        sheetId: String,
        refreshData: Boolean = false,
    ): ApiResult<String, Any> =
        apiTextResult {
            client.get {
                url("https://docs.google.com/spreadsheets/d/$spreadsheetId/gviz/tq")
                parameter("gid", sheetId)
                header("X-DataSource-Auth", true)
                if (refreshData) {
                    parameter("refreshData", getTimeMillis())
                }
            }
        }
like image 68
Elad Finish Avatar answered Dec 16 '25 09:12

Elad Finish