Skip to content

Instantly share code, notes, and snippets.

@Jeff-Soares
Last active September 15, 2021 21:42
Show Gist options
  • Select an option

  • Save Jeff-Soares/82e9b53edcb64a171567447729fd6ff1 to your computer and use it in GitHub Desktop.

Select an option

Save Jeff-Soares/82e9b53edcb64a171567447729fd6ff1 to your computer and use it in GitHub Desktop.
Simple HTTP request using standard library
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.StringBuilder
import java.net.HttpURLConnection
import java.net.URL
private fun simpleHttpRequest(): JokeResponse? {
val responseString = StringBuilder()
val url = URL("https://icanhazdadjoke.com/")
val conn = (url.openConnection() as HttpURLConnection).apply {
requestMethod = "GET"
addRequestProperty("Accept", "application/json")
}
BufferedReader(InputStreamReader(conn.inputStream))
.readLine()
.forEach {
responseString.append(it)
}
val jsonAdapter = Moshi.Builder()
.addLast(KotlinJsonAdapterFactory())
.build()
.adapter(JokeResponse::class.java)
return jsonAdapter.fromJson(responseString.toString())
}
data class JokeResponse(val id: String, val joke: String, val status: Int)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment