Skip to main content

Introduction to OkHTTP

Introduction to OkHTTP

OkHTTP is a popular open-source HTTP client library for Android and Java applications. It is developed by Square and provides a simple and efficient way to make HTTP requests and handle responses. OkHTTP offers features such as connection pooling, transparent gzip compression, request/response interception, and much more.

In this tutorial, we will explore the features of OkHTTP and learn how to install and use it in a Kotlin Android project.

Features of OkHTTP

OkHTTP offers a wide range of features that make it a powerful HTTP client library. Some of its notable features include:

  1. Efficient HTTP Requests: OkHTTP allows you to make synchronous and asynchronous HTTP requests with ease. It handles connections, reuses them, and efficiently manages the request/response flow.

  2. Connection Pooling: OkHTTP uses connection pooling to reuse established connections, which reduces the overhead of creating new connections for subsequent requests.

  3. Transparent Gzip Compression: OkHTTP automatically compresses and decompresses the request/response bodies using Gzip compression, which reduces the payload size and improves performance.

  4. Request/Response Interception: OkHTTP provides an interceptor mechanism that allows you to intercept and modify HTTP requests and responses. This feature is useful for adding custom headers, logging, or modifying the request/response data.

  5. Caching: OkHTTP supports HTTP caching by default, allowing you to cache responses and serve them from the cache for subsequent requests. This feature helps reduce network traffic and improves performance.

  6. TLS/SSL Support: OkHTTP supports TLS/SSL encryption, allowing you to establish secure connections with HTTPS servers.

  7. WebSocket Support: OkHTTP provides WebSocket support, allowing you to establish WebSocket connections and communicate with WebSocket servers.

Installation

To use OkHTTP in your Kotlin Android project, you need to add the OkHTTP dependency to your project's build.gradle file.

  1. Open your project in Android Studio.

  2. Open the build.gradle file for your app module.

  3. Add the following dependency in the dependencies block:

implementation 'com.squareup.okhttp3:okhttp:4.9.1'
  1. Sync the project to download the OkHTTP library.

Usage

Now that you have installed OkHTTP in your project, let's see how to use it to make HTTP requests.

Synchronous Request

To make a synchronous HTTP request using OkHTTP, follow these steps:

  1. Create an instance of the OkHttpClient class:
val client = OkHttpClient()
  1. Create a Request object with the URL you want to request:
val request = Request.Builder()
.url("https://api.example.com/data")
.build()
  1. Execute the request using the OkHttpClient instance:
val response = client.newCall(request).execute()
  1. Get the response body as a string:
val responseBody = response.body?.string()
  1. Optionally, handle the response or any exceptions:
if (response.isSuccessful) {
// Handle successful response
println(responseBody)
} else {
// Handle unsuccessful response
println("Error: ${response.code}")
}

Asynchronous Request

To make an asynchronous HTTP request using OkHTTP, follow these steps:

  1. Create an instance of the OkHttpClient class:
val client = OkHttpClient()
  1. Create a Request object with the URL you want to request:
val request = Request.Builder()
.url("https://api.example.com/data")
.build()
  1. Execute the request asynchronously using the OkHttpClient instance:
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
val responseBody = response.body?.string()
// Handle the response
println(responseBody)
}

override fun onFailure(call: Call, e: IOException) {
// Handle the failure
println("Error: ${e.message}")
}
})

Request/Response Interception

OkHTTP allows you to intercept and modify HTTP requests and responses using interceptors. Here's an example of adding a custom header to a request:

val client = OkHttpClient.Builder()
.addInterceptor(object : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request().newBuilder()
.addHeader("CustomHeader", "Value")
.build()
return chain.proceed(request)
}
})
.build()

In this example, we added an interceptor to the OkHttpClient that adds a custom header to every request.

OkHttp Examples