Skip to content

Instantly share code, notes, and snippets.

@surfmuggle
Forked from Da9el00/Main.kt
Last active January 23, 2024 21:49
Show Gist options
  • Save surfmuggle/22226d1cd16097870951fcff448b2a20 to your computer and use it in GitHub Desktop.
Save surfmuggle/22226d1cd16097870951fcff448b2a20 to your computer and use it in GitHub Desktop.
Kotlin - Making API Calls in Kotlin Without External Libraries
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()
}
}
@surfmuggle
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment