kotlin http request
snippet in kotlin

kotlin http request

user933

URL("https://google.com").readText()

kotlin http request

user1186

import com.google.api.client.json.Json
import okhttp3.*

private val client = OkHttpClient()

fun String.get(token: String): Response = request(token).get().execute()

fun String.post(data: String, token: String): Response {
    val json = MediaType.get(Json.MEDIA_TYPE)
    val body = RequestBody.create(json, "{\"data\":\"$data\"}")
    val request = request(token).post(body).build()
    return request.execute()
}

fun String.request(token: String): Request.Builder = Request.Builder()
    .addHeader("Authorization", "Bearer $token")
    .url(this)

private fun Request.Builder.execute(): Response = build().execute()
private fun Request.execute(): Response = client.newCall(this).execute()