This is my small utility method to fetch an Image from internet
object HttpClient {
private val connectTimeout = 15000
private val readTimeout = 15000
private val requestMethod = "GET"
def getBytes(inline url: String) = Try {
println("fetching data...")
val connection =
(new URL(url)).openConnection.asInstanceOf[HttpURLConnection]
connection.setConnectTimeout(connectTimeout)
connection.setReadTimeout(readTimeout)
connection.setRequestMethod(requestMethod)
val inputStream = connection.getInputStream
val bytes = inputStream.readAllBytes()
println("DONE")
if (inputStream != null) inputStream.close
bytes
}.toOption
}
And below is the code consuming it to fetch an image convert to string and print it.
object Test extends App {
val url = "<some random http url of an image>"
val bytes = HttpClient.getBytes(url).getOrElse(Array.empty[Byte])
val img = java.util.Base64.getEncoder.encodeToString(bytes)
println(img)
}
It works correctly, but I am trying to fetch the image at compile time and print it on runtime.
Is this possible in Scala 3?
If yes, how?