Coverage Summary for Class: HttpTextClient_jvmAndroidKt (com.georgeci.moneysurfer.data.remote)
| Class |
Method, %
|
Branch, %
|
Line, %
|
Instruction, %
|
| HttpTextClient_jvmAndroidKt |
100%
(2/2)
|
|
100%
(2/2)
|
100%
(16/16)
|
| HttpTextClient_jvmAndroidKt$httpGetText$2 |
100%
(1/1)
|
75%
(6/8)
|
85.7%
(12/14)
|
84.9%
(129/152)
|
| Total |
100%
(3/3)
|
75%
(6/8)
|
87.5%
(14/16)
|
86.3%
(145/168)
|
package com.georgeci.moneysurfer.data.remote
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.withContext
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URI
/** `HttpURLConnection` defaults to *no* timeout, so both halves have to be set explicitly. */
private const val TIMEOUT_MILLIS = 15_000
private val HTTP_OK_RANGE = 200..299
/**
* JVM and Android share the same `java.net` stack, so the actual lives once here rather than as
* two byte-identical twins — the same reasoning as `data-local`'s `BackupCrypto`.
*/
internal actual suspend fun httpGetText(url: String): String = withContext(Dispatchers.IO) {
val connection = try {
(URI(url).toURL().openConnection() as HttpURLConnection)
} catch (error: IOException) {
throw HttpRequestException("Cannot open $url", error)
} catch (error: IllegalArgumentException) {
throw HttpRequestException("Malformed URL: $url", error)
}
connection.requestMethod = "GET"
connection.connectTimeout = TIMEOUT_MILLIS
connection.readTimeout = TIMEOUT_MILLIS
connection.setRequestProperty("Accept", "application/json")
try {
val status = connection.responseCode
if (status !in HTTP_OK_RANGE) {
throw HttpRequestException("HTTP $status from $url")
}
connection.inputStream.bufferedReader().use { it.readText() }
} catch (error: IOException) {
throw HttpRequestException("GET $url failed", error)
} finally {
connection.disconnect()
}
}