Last active
September 15, 2021 21:42
-
-
Save Jeff-Soares/82e9b53edcb64a171567447729fd6ff1 to your computer and use it in GitHub Desktop.
Simple HTTP request using standard library
This file contains hidden or 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.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