Android中如何获取指定URL的非缓存版本文件?
我来帮你搞定在Android里获取这两个GitHub raw文件非缓存版本的问题,之前用Fuel没成功的话,咱们试试这几个靠谱的方案,不管是第三方库还是原生API都能解决:
方案1:使用OkHttp(推荐,灵活可控)
OkHttp是Android开发中非常常用的网络库,对缓存控制的支持很完善。你可以通过设置请求头强制跳过缓存,直接从服务器拉取最新内容:
import okhttp3.OkHttpClient import okhttp3.Request // 初始化OkHttpClient(建议全局单例) val client = OkHttpClient() fun fetchNonCachedVersion(url: String) { val request = Request.Builder() .url(url) // 添加缓存控制头,强制不使用缓存,必须从服务器获取最新内容 .header("Cache-Control", "no-cache, no-store, must-revalidate") .header("Pragma", "no-cache") // 兼容旧HTTP 1.0协议 .build() client.newCall(request).enqueue(object : okhttp3.Callback { override fun onFailure(call: okhttp3.Call, e: java.io.IOException) { // 处理请求失败 } override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) { response.body?.let { body -> val content = body.string() // 处理最新获取到的文件内容 } } }) } // 调用方法获取两个URL的内容 fetchNonCachedVersion("https://github.com/vedantroy/image-test/raw/master/version.txt") fetchNonCachedVersion("https://raw.githubusercontent.com/vedantroy/image-test/master/version.txt")
方案2:修复Fuel的请求配置
如果你还是想用Fuel,可能之前没正确配置缓存控制的请求头。试试下面的写法,明确告诉客户端和服务器不要使用缓存:
import com.github.kittinunf.fuel.Fuel fun fetchWithFuel(url: String) { Fuel.get(url) // 设置缓存控制头,彻底禁用缓存 .header("Cache-Control" to "no-cache, no-store, must-revalidate") .header("Pragma" to "no-cache") .responseString { _, _, result -> result.fold( success = { content -> // 处理最新内容 }, failure = { error -> // 处理错误 } ) } }
方案3:原生HttpURLConnection(无需第三方库)
如果不想引入第三方库,用Android自带的HttpURLConnection也能实现,核心同样是设置缓存控制头:
import java.net.HttpURLConnection import java.net.URL fun fetchWithNative(urlString: String) { Thread { try { val url = URL(urlString) val connection = url.openConnection() as HttpURLConnection connection.requestMethod = "GET" // 禁用缓存 connection.setRequestProperty("Cache-Control", "no-cache, no-store, must-revalidate") connection.setRequestProperty("Pragma", "no-cache") connection.doInput = true val inputStream = connection.inputStream val content = inputStream.bufferedReader().readText() // 处理内容(注意:更新UI要切换到主线程) inputStream.close() connection.disconnect() } catch (e: Exception) { e.printStackTrace() } }.start() }
额外技巧:绕过CDN缓存
GitHub的raw文件会经过CDN缓存,有时候即使客户端设置了缓存头,CDN可能还是返回缓存内容。这时候可以在URL末尾添加一个随机参数(比如时间戳),让每次请求的URL都不一样,彻底绕过所有缓存:
val timestamp = System.currentTimeMillis() val nonCachedUrl = "https://github.com/vedantroy/image-test/raw/master/version.txt?=$timestamp" // 用上面的任意方法请求这个nonCachedUrl即可
这个方法简单粗暴,适合所有场景,尤其是遇到CDN缓存无法通过请求头绕过的情况。
内容的提问来源于stack exchange,提问作者Foobar
相关产品推荐
相关产品推荐

