Kotlin HTTP GET JSON field with timeouts
Kotlin
import java.net.HttpURLConnection
import java.net.URI
fun getJsonField(url: String, field: String): String? {
val conn = URI(url).toURL().openConnection() as HttpURLConnection
conn.connectTimeout = 3_000
conn.readTimeout = 5_000
val body = try {
check(conn.responseCode in 200..299) { "HTTP ${conn.responseCode} for $url" }
conn.inputStream.bufferedReader().use { it.readText() }
} finally {
conn.disconnect()
}
val keyAt = body.indexOf('"' + field + '"')
if (keyAt < 0) return null
val colonAt = body.indexOf(':', keyAt)
if (colonAt < 0) return null
val from = body.indexOf('"', colonAt + 1)
val to = body.indexOf('"', from + 1)
// minimal quoted-string scan; use a real JSON parser for nested data
return if (from < 0 || to < 0) null else body.substring(from + 1, to)
}