free geoip
143

Using OkHttp in Kotlin for HTTP Networking

If you’re building Android applications in Kotlin, networking is a fundamental part of most apps whether you’re fetching data from…

If you’re building Android applications in Kotlin, networking is a fundamental part of most apps whether you’re fetching data from a REST API or uploading files to a server. One of the most reliable and efficient HTTP clients for Android is OkHttp, a powerful library developed by Square that handles everything from making basic requests to advanced connection pooling and interceptors.

Using OkHttp in Kotlin for HTTP Networking

In this article, you’ll learn how to use OkHttp with Kotlin to send GET and POST requests, handle responses, and work with interceptors to manage headers or log network activity.

Getting Started with OkHttp in Kotlin

To start using OkHttp, add the dependency to your build.gradle file:

implementation("com.squareup.okhttp3:okhttp:4.12.0")

This brings the latest stable version of the OkHttp library into your project.

Making a Simple GET Request

You can perform a GET request using OkHttp’s OkHttpClient and Request classes. Here’s a simple example:

val client = OkHttpClient()

val request = Request.Builder()
    .url("https://jsonplaceholder.typicode.com/posts")
    .build()

client.newCall(request).enqueue(object : Callback {
    override fun onFailure(call: Call, e: IOException) {
        Log.e("HTTP GET", "Network Error", e)
    }

    override fun onResponse(call: Call, response: Response) {
        response.body?.let { responseBody ->
            val result = responseBody.string()
            Log.d("HTTP GET", result)
        }
    }
})

This request is made asynchronously and logs the result once a response is received.

Sending a POST Request with JSON Body

Sending a POST request is also straightforward. You can build a request body using RequestBody.create() with the appropriate media type:

val client = OkHttpClient()

val jsonMediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody = """
    {
        "title": "OkHttp in Kotlin",
        "body": "This is a POST request example.",
        "userId": 1
    }
""".trimIndent()

val requestBody = jsonBody.toRequestBody(jsonMediaType)

val request = Request.Builder()
    .url("https://jsonplaceholder.typicode.com/posts")
    .post(requestBody)
    .build()

client.newCall(request).enqueue(object : Callback {
    override fun onFailure(call: Call, e: IOException) {
        Log.e("HTTP POST", "Request failed", e)
    }

    override fun onResponse(call: Call, response: Response) {
        response.body?.let { responseBody ->
            val result = responseBody.string()
            Log.d("HTTP POST", result)
        }
    }
})

Adding Interceptors

Interceptors can be used for logging, modifying requests, or handling authentication:

val loggingInterceptor = HttpLoggingInterceptor().apply {
    level = HttpLoggingInterceptor.Level.BODY
}

val client = OkHttpClient.Builder()
    .addInterceptor(loggingInterceptor)
    .build()

This will log all request and response details, making debugging easier.

Why Use OkHttp with Kotlin?

OkHttp integrates smoothly with Kotlin and is known for its performance, ease of use, and flexibility. Whether you’re developing apps using REST APIs, uploading files, or dealing with web sockets, OkHttp is an essential tool.

Moreover, OkHttp supports coroutines via extensions like Kotlinx Coroutines, allowing even more elegant handling of asynchronous code.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *