Here is my code:
val client = HttpClient(CIO)
try {
val apiKey = “key”
val response: HttpResponse = client.get("https://api.flightaware.com/api/flights/search") {
header("x-apikey", apiKey)
parameter("query", "-latlong \"51.442 -0.520 51.491 -0.370\"")
parameter("max_pages", 1)
}
val responseBody: String = response.body()
val aircraftList = mutableListOf<String>()
if (responseBody.isNotEmpty()) {
try {
val jsonResponse = JSONObject(responseBody)
val flights = jsonResponse.optJSONArray("flights")
if (flights != null) {
for (i in 0 until flights.length()) {
val flight = flights.getJSONObject(i)
val ident = flight.optString("ident", "Unknown Ident")
val origin = flight.getJSONObject("origin").optString("name", "Unknown Origin")
val destination = flight.getJSONObject("destination").optString("name", "Unknown Destination")
val altitude = flight.getJSONObject("last_position").optInt("altitude", 0)
val latitude = flight.getJSONObject("last_position").optDouble("latitude", 0.0)
val longitude = flight.getJSONObject("last_position").optDouble("longitude", 0.0)
val heading = flight.getJSONObject("last_position").optInt("heading", 0)
aircraftList.add("Flight: $ident\nOrigin: $origin\nDestination: $destination\nAltitude: $altitude feet\nCoordinates: ($latitude, $longitude)\nHeading: $heading°\n-----")
}
} else {
println("No flights")
}
} catch (e: Exception) {
println("Error: ${e.message}")
}
} else {
println("Empty response body")
}
withContext(Dispatchers.Main) {
val textView = findViewById<TextView>(R.id.tvText)
textView.text = aircraftList.joinToString("\n\n")
}
} catch (e: Exception) {
println("Error making request: ${e.message}")
withContext(Dispatchers.Main) {
val textView = findViewById<TextView>(R.id.tvText)
textView.text = "Error fetching flight data: ${e.message}"
}
} finally {
client.close()
}
I keep getting this response: “Error fetching flight data: null”. My API key works as I have tested it on the website and Im just wondering what went wrong here. I’m trying to get the api to return all flights within a box of coordinates.
Thank you.