Last active
October 28, 2019 22:25
-
-
Save mantono/6ace6f05b88db467261ed158a792d5fa to your computer and use it in GitHub Desktop.
OkHttp extensions in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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