Making requests become super easy in favor of okhttp3. This example implementation would help you to understand and create your own http client in kotlin and send requests.

Dependencies

Let's start with the dependencies, so that you don't forget to add

dependencies {
    implementation("com.squareup.okhttp3:okhttp:4.4.0")
}

How to set timeout in kotlin HTTP requests

If you would like to add timeouts in your client, please modify your httpClient like this:

private val httpClient by lazy {
    OkHttpClient.Builder()
        .connectTimeout(MY_CONNECT_TIMEOUT, TimeUnit.SECONDS)
        .readTimeout(MY_READ_TIMEOUT, TimeUnit.SECONDS)
        .writeTimeout(MY_WRITE_TIMEOUT, TimeUnit.SECONDS)
        .build()

}

How to add basic authentication in OKHTTP3

If you want to add any headers we can user addHeader() method to achieve this. Similarly we can send basic authentication credential in the request like below.

val request = Request.Builder()
    .url(url)
    .addHeader("Authorization", Credentials.basic("username", "password"))
    .post(requestBody.toRequestBody(mediaType))
    .build()

How to send GET request in Kotlin

val request = Request.Builder().url(url).get().build()
OkHttpClient.Builder().build().newCall(request).execute()

How to send POST request in Kotlin

val request = Request.Builder()
            .url(url)
            .post(requestBody.toRequestBody(mediaType))
            .build()

OkHttpClient.Builder().build().newCall(request).execute()

How to send PUT request in Kotlin

val request = Request.Builder()
            .url(url)
            .put(requestBody.toRequestBody(mediaType))
            .build()

OkHttpClient.Builder().build().newCall(request).execute()

How to send PATCH request in Kotlin

val request = Request.Builder()
            .url(url)
            .patch(requestBody.toRequestBody(mediaType))
            .build()

OkHttpClient.Builder().build().newCall(request).execute()