-
-
Save surfmuggle/22226d1cd16097870951fcff448b2a20 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 | |
// add proxy support if your pc is behind a corporate proxy | |
System.setProperty("java.net.useSystemProxies", "true"); | |
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
Added support for using it behind a proxy taken from https://stackoverflow.com/a/11527488/819887 and also view the related tutorial https://www.youtube.com/watch?v=2DNrBFe1UW4