-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathHTTPLoader.kt
More file actions
37 lines (31 loc) · 1.06 KB
/
HTTPLoader.kt
File metadata and controls
37 lines (31 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.margelo.nitro.rive
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL
sealed class HTTPLoaderException(message: String) : Exception(message) {
class InvalidURL(url: String) : HTTPLoaderException("Invalid URL: $url")
class HttpError(val statusCode: Int, url: String) :
HTTPLoaderException("HTTP error $statusCode for $url")
}
object HTTPLoader {
suspend fun downloadBytes(url: String): ByteArray = withContext(Dispatchers.IO) {
val urlObj = try {
URL(url)
} catch (e: MalformedURLException) {
throw HTTPLoaderException.InvalidURL(url)
}
val connection = urlObj.openConnection() as HttpURLConnection
try {
connection.requestMethod = "GET"
val statusCode = connection.responseCode
if (statusCode !in 200..299) {
throw HTTPLoaderException.HttpError(statusCode, url)
}
connection.inputStream.use { it.readBytes() }
} finally {
connection.disconnect()
}
}
}