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.
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())
}
}
}
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