android - 在 Okhttp3 上使用 HttpURLConnection 有什么好处吗?
问题描述
我正在从互联网上拉下一个简单的 xml 文件并通过XmlPullParser
. 我一直在使用HttpURLConnection
which 似乎工作正常,但后来我开始玩弄OkhttpClient
所以现在我想知道是否/什么时候使用更好HttpUrlConnection
。 Okhttp
实施当然感觉更干净。
// 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
}
解决方案
推荐阅读
- javascript - 如何在新 div 中包装每三个唯一的子元素
- database - 如何模拟 ping 命令
- jmeter - 即使在生产中关闭了代码,我的 Jmeter 脚本也通过了
- repo - 回购初始化停止总是检查最新的回购
- docker - 运行 Docker 构建时出现未指定的错误 (0x80004005)
- heap-memory - 在 cloudwatch 中收集 JVM 指标,例如堆使用情况 GC 信息以获取 Fargate 服务
- sharepoint - 在 sharepoint 现代网站上嵌入最新的网络聊天
- typescript - 如何在异步方法中返回承诺?
- jquery - 在 wordpress upolad 媒体窗口上显示自定义消息?
- python - 如何将嵌套的 JSON 转换为 Pandas 数据框?