Skip to content

Instantly share code, notes, and snippets.

@lamvann
Created March 9, 2020 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lamvann/d441b2529d4f3b164edc5947401a1e4f to your computer and use it in GitHub Desktop.
Save lamvann/d441b2529d4f3b164edc5947401a1e4f to your computer and use it in GitHub Desktop.
import io.ktor.client.HttpClient
import io.ktor.client.features.json.JsonFeature
import io.ktor.client.features.json.serializer.KotlinxSerializer
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.readText
import io.ktor.http.URLProtocol.Companion.HTTPS
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.UnstableDefault
import kotlinx.serialization.json.Json
@Serializable
data class Item(
val date: String,
val explanation: String,
val hdurl: String,
@SerialName("media_type") val mediaType: String,
@SerialName("service_version") val serviceVersion: String,
val title: String,
val url: String
)
@UnstableDefault
@ExperimentalStdlibApi
class NasaApi {
private val client = HttpClient(httpEngine) {
install(JsonFeature) {
serializer = KotlinxSerializer()
}
}
fun info(callback: (Item) -> Unit) {
GlobalScope.launch {
val rawResponse = client.get<HttpResponse> {
url {
protocol = HTTPS
host = "api.nasa.gov"
encodedPath = "planetary/apod"
parameter("api_key", "???") // This has the correct api key in my project
}
}
val parsedResult = Json.parse(Item.serializer(), rawResponse.readText())
callback(parsedResult)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment