okhttp kotlin example
val BASE_URL = "https://api.unsplash.com"
val ACCESS_KEY = "..."
val path = "/photos/$id"
val uri = Uri.parse(BASE_URL)
.buildUpon()
.appendEncodedPath(path)
//.appendPath(path)
.build()
val client = OkHttpClient()
val request = Request.Builder()
.url(uri.toString())
.addHeader("Accept-Version", "v1")
.addHeader("Authorization", "Client-ID $ACCESS_KEY")
.get()
.build()
val response = client.newCall(request).execute()
val jsonDataString = response.body()?.string()
val json = JSONObject(jsonDataString)
if (!response.isSuccessful) {
val errors = json.getJSONArray("errors").join(", ")
throw Exception(errors)
}
val rawUrl = json.getJSONObject("urls").getString("raw")
3
1
private val client = OkHttpClient()
fun run() {
val request = Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) throw IOException("Unexpected code $response")
for ((name, value) in response.headers) {
println("$name: $value")
}
println(response.body!!.string())
}
}
})
}
Thank you!
1
0
Are there any code examples left?
New code examples in category Kotlin
-
Kotlin 2022-03-27 07:55:32 kotlin split by uppercase
-
Kotlin 2022-03-27 07:40:17 var and val in kotlin
-
Kotlin 2022-03-20 03:10:23 kotlin Random()
-
Kotlin 2022-03-18 00:40:01 exported android manifest
-
Kotlin 2022-03-16 05:25:02 coroutines kotlin android dependency
-
Kotlin 2022-03-14 18:05:24 arrayadapter spinner kotlin fragment
-
Kotlin 2022-03-07 04:30:37 spring boot kotlin
-
Kotlin 2022-03-06 06:05:06 kotlin scope functions
-
Kotlin 2022-02-28 03:15:02 handler kotlin