Square's meticulous HTTP client for Java and Kotlin
—
Pluggable request and response transformation framework for monitoring, rewriting, and retry logic.
interface Interceptor {
fun intercept(chain: Chain): Response
interface Chain {
fun request(): Request
fun proceed(request: Request): Response
fun connection(): Connection?
fun call(): Call
fun connectTimeoutMillis(): Int
fun withConnectTimeout(timeout: Int, unit: TimeUnit): Chain
fun readTimeoutMillis(): Int
fun withReadTimeout(timeout: Int, unit: TimeUnit): Chain
fun writeTimeoutMillis(): Int
fun withWriteTimeout(timeout: Int, unit: TimeUnit): Chain
}
}val client = OkHttpClient.Builder()
.addInterceptor(applicationInterceptor) // Application-level
.addNetworkInterceptor(networkInterceptor) // Network-level
.build()class LoggingInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val t1 = System.nanoTime()
println("Sending request ${request.url}")
val response = chain.proceed(request)
val t2 = System.nanoTime()
println("Received response for ${response.request.url} in ${(t2 - t1) / 1e6} ms")
return response
}
}class AuthInterceptor(private val token: String) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request().newBuilder()
.addHeader("Authorization", "Bearer $token")
.build()
return chain.proceed(request)
}
}class RetryInterceptor(private val maxRetries: Int = 3) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
var response = chain.proceed(request)
var retryCount = 0
while (!response.isSuccessful && retryCount < maxRetries) {
retryCount++
response.close()
response = chain.proceed(request)
}
return response
}
}class CacheInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
// Modify request based on network availability
val cacheControl = if (isNetworkAvailable()) {
CacheControl.Builder()
.maxAge(5, TimeUnit.MINUTES)
.build()
} else {
CacheControl.Builder()
.onlyIfCached()
.maxStale(7, TimeUnit.DAYS)
.build()
}
val cacheRequest = request.newBuilder()
.cacheControl(cacheControl)
.build()
return chain.proceed(cacheRequest)
}
}Install with Tessl CLI
npx tessl i tessl/maven-com-squareup-okhttp3--okhttp