0
# Caching
1
2
HTTP response caching to improve performance and reduce network usage.
3
4
## Cache
5
6
Stores HTTP responses for reuse to avoid redundant network requests.
7
8
```kotlin { .api }
9
class Cache(directory: File, maxSize: Long) : Closeable, Flushable {
10
val directory: File
11
val directoryPath: Path
12
13
fun delete()
14
fun evictAll()
15
fun urls(): MutableIterator<String>
16
fun size(): Long
17
fun maxSize(): Long
18
fun flush()
19
fun close()
20
fun writeAbortCount(): Int
21
fun writeSuccessCount(): Int
22
fun networkCount(): Int
23
fun hitCount(): Int
24
fun requestCount(): Int
25
}
26
```
27
28
### Cache Usage
29
30
```kotlin
31
// Create cache directory
32
val cacheDirectory = File(context.cacheDir, "http_cache")
33
val cacheSize = 10L * 1024 * 1024 // 10 MiB
34
35
// Configure client with cache
36
val client = OkHttpClient.Builder()
37
.cache(Cache(cacheDirectory, cacheSize))
38
.build()
39
```
40
41
## CacheControl
42
43
Directives that control HTTP caching behavior.
44
45
```kotlin { .api }
46
class CacheControl private constructor() {
47
val noCache: Boolean
48
val noStore: Boolean
49
val maxAgeSeconds: Int
50
val sMaxAgeSeconds: Int
51
val isPrivate: Boolean
52
val isPublic: Boolean
53
val mustRevalidate: Boolean
54
val maxStaleSeconds: Int
55
val minFreshSeconds: Int
56
val onlyIfCached: Boolean
57
val noTransform: Boolean
58
val immutable: Boolean
59
60
override fun toString(): String
61
62
companion object {
63
val FORCE_NETWORK: CacheControl
64
val FORCE_CACHE: CacheControl
65
66
fun parse(headers: Headers): CacheControl
67
}
68
}
69
```
70
71
### CacheControl Builder
72
73
```kotlin { .api }
74
class CacheControl.Builder {
75
fun noCache(): Builder
76
fun noStore(): Builder
77
fun maxAge(maxAge: Int, timeUnit: TimeUnit): Builder
78
fun maxAge(maxAge: Duration): Builder
79
fun maxStale(maxStale: Int, timeUnit: TimeUnit): Builder
80
fun maxStale(maxStale: Duration): Builder
81
fun minFresh(minFresh: Int, timeUnit: TimeUnit): Builder
82
fun minFresh(minFresh: Duration): Builder
83
fun onlyIfCached(): Builder
84
fun noTransform(): Builder
85
fun immutable(): Builder
86
fun build(): CacheControl
87
}
88
```
89
90
### Cache Control Examples
91
92
```kotlin
93
// Force network request (skip cache)
94
val request = Request.Builder()
95
.url("https://api.example.com/data")
96
.cacheControl(CacheControl.FORCE_NETWORK)
97
.build()
98
99
// Only use cached response (don't make network request)
100
val cachedRequest = Request.Builder()
101
.url("https://api.example.com/data")
102
.cacheControl(CacheControl.FORCE_CACHE)
103
.build()
104
105
// Custom cache control
106
val cacheControl = CacheControl.Builder()
107
.maxAge(5, TimeUnit.MINUTES)
108
.maxStale(1, TimeUnit.HOURS)
109
.build()
110
111
val request = Request.Builder()
112
.url("https://api.example.com/data")
113
.cacheControl(cacheControl)
114
.build()
115
```