Scala HTTP JSON GET with hard timeouts
Scala
import java.net.URI
import java.net.http.{HttpClient, HttpRequest, HttpResponse}
import java.time.Duration
def fetchJsonField(url: String, field: String, timeout: Duration = Duration.ofSeconds(5)): Either[String, String] =
try
val client = HttpClient.newBuilder().connectTimeout(timeout).build()
val request = HttpRequest.newBuilder(URI.create(url)).timeout(timeout)
.header("Accept", "application/json").GET().build()
val response = client.send(request, HttpResponse.BodyHandlers.ofString())
if response.statusCode() != 200 then Left(s"HTTP ${response.statusCode()} for $url")
else
val body = response.body()
val keyAt = body.indexOf(field)
val colon = if keyAt < 0 then -1 else body.indexOf(':', keyAt + field.length)
val open = if colon < 0 then -1 else body.indexOf('"', colon + 1)
val close = if open < 0 then -1 else body.indexOf('"', open + 1)
if close < 0 then Left(s"JSON field '$field' not found") else Right(body.substring(open + 1, close))
catch case e: Exception => Left(s"request failed: ${e.getMessage}")