Last active
January 13, 2020 00:11
-
-
Save sureshbabua8/35ac5bbd5b4e4ee39ad32db9a0d5869c to your computer and use it in GitHub Desktop.
Simple GET Request 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
import com.squareup.moshi.JsonClass | |
import com.squareup.moshi.Moshi | |
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory | |
import okhttp3.OkHttpClient | |
import okhttp3.Request | |
import java.io.IOException | |
class ParseResponseWithMoshi { | |
private val client = OkHttpClient() | |
private val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build() | |
private val gistJsonAdapter = moshi.adapter(Gist::class.java) | |
fun run() { | |
val request = Request.Builder() | |
.url("https://api.nasa.gov/neo/rest/v1/neo/browse?api_key=DEMO_KEY") | |
.build() | |
client.newCall(request).execute().use { response -> | |
if (!response.isSuccessful) throw IOException("Unexpected code $response") | |
val gist = gistJsonAdapter.fromJson(response.body!!.source()) | |
for (key in gist!!.near_earth_objects!!) { | |
println(key.name) // lists the name of every astronomical object near Earth | |
} | |
} | |
} | |
@JsonClass(generateAdapter = true) | |
data class Gist(var near_earth_objects: List<GistFile>) | |
@JsonClass(generateAdapter = true) | |
data class GistFile(var name: String?) | |
} | |
fun main() { | |
ParseResponseWithMoshi().run() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment