Created
September 24, 2023 12:39
-
-
Save Da9el00/a29b4acca9dec698e18f88fca2eb8c96 to your computer and use it in GitHub Desktop.
Kotlin - Making API Calls in Kotlin Without External Libraries
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 java.io.BufferedReader | |
import java.io.InputStreamReader | |
import java.net.HttpURLConnection | |
import java.net.URI | |
import java.net.URL | |
fun main() { | |
val apiUrl = "https://catfact.ninja/fact" //API endpoint | |
try { | |
val url : URL = URI.create(apiUrl).toURL() | |
val connection : HttpURLConnection = url.openConnection() as HttpURLConnection | |
//Request method: GET | |
connection.requestMethod = "GET" | |
// Response code | |
val responseCode: Int = connection.responseCode | |
println("Response Code: $responseCode") | |
if (responseCode == HttpURLConnection.HTTP_OK) { | |
// Read and print the response data | |
val reader : BufferedReader = BufferedReader(InputStreamReader(connection.inputStream)) | |
var line: String? | |
val response = StringBuilder() | |
while (reader.readLine().also { line = it } != null) { | |
response.append(line) | |
} | |
reader.close() | |
println("Response Data: $response") | |
} else { | |
println("Error: Unable to fetch data from the API") | |
} | |
// Close the connection | |
connection.disconnect() | |
} catch (e: Exception) { | |
e.printStackTrace() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment