I'm pulling down a simple xml file from the internet and feeding it through XmlPullParser
. I'd been using HttpURLConnection
which seems to work fine, but then I started playing around with OkhttpClient
so now I'm wondering if/when it's a better to use HttpUrlConnection
. Okhttp
implementation certainly feels cleaner.
// For Example
@Suppress("BlockingMethodInNonBlockingContext")
suspend fun fetchRss(): List<RssItem> = withContext(Dispatchers.IO) {
var rssList: List<RssItem> = emptyList()
try {
val url = URL(RSS)
val connection: HttpURLConnection = url.openConnection() as HttpURLConnection
connection.apply {
readTimeout = 10000 // in millis
connectTimeout = 15000
requestMethod = "GET"
connect()
}
val input: InputStream = connection.inputStream
rssList = parseRss(input) as ArrayList<RssItem>
input.close()
} catch (e: Exception) {
e.printStackTrace()
}
return@withContext rssList
}
@Suppress("BlockingMethodInNonBlockingContext")
suspend fun fetchRssWithOkhttp(): List<RssItem> = withContext(Dispatchers.IO) {
val client = OkHttpClient().newBuilder().build()
val request = Request.Builder().url(RSS).build()
var rssList: List<RssItem> = emptyList()
try {
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
rssList = parseRss(response.body()!!.byteStream())
response.close()
}
} catch (e: Exception){
e.printStackTrace()
}
return@withContext rssList
}