首页 > 解决方案 > 在 Okhttp3 上使用 HttpURLConnection 有什么好处吗?

问题描述

我正在从互联网上拉下一个简单的 xml 文件并通过XmlPullParser. 我一直在使用HttpURLConnectionwhich 似乎工作正常,但后来我开始玩弄OkhttpClient所以现在我想知道是否/什么时候使用更好HttpUrlConnectionOkhttp实施当然感觉更干净。

// 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
    }

标签: androidkotlinhttpurlconnectionokhttp

解决方案


推荐阅读