plain kotlin http request code example
Example 1: kotlin http request
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()
Example 2: kotlin http request
URL("https://google.com").readText()