Skip to content

Instantly share code, notes, and snippets.

@mantono
Last active October 28, 2019 22:25
Show Gist options
  • Save mantono/6ace6f05b88db467261ed158a792d5fa to your computer and use it in GitHub Desktop.
Save mantono/6ace6f05b88db467261ed158a792d5fa to your computer and use it in GitHub Desktop.
OkHttp extensions in Kotlin
package com.mantono
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.util.concurrent.CompletableFuture
private const val MEDIA_TYPE_JSON = "application/json; charset=utf-8"
fun jsonRequest(data: Any): RequestBody {
val json: String = jacksonObjectMapper().writeValueAsString(data)
val mediaType: MediaType = MEDIA_TYPE_JSON.toMediaType()
return json.toRequestBody(mediaType)
}
/**
* Use a [Callback] to make an asynchronous request with OkHttp
* and receive a [CompletableFuture] for type [T] given the
* transform function [transform].
*/
fun <T> Call.Factory.asyncRequest(
request: Request,
future: CompletableFuture<T> = CompletableFuture(),
transform: (call: Call, response: Response) -> T
): CompletableFuture<T> {
val callback = object: Callback {
override fun onFailure(call: Call, e: IOException) {
future.completeExceptionally(e)
}
override fun onResponse(call: Call, response: Response) {
future.complete(transform(call, response))
}
}
this.newCall(request).enqueue(callback)
return future
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment