如何在DownloadManager中启用HTTP响应缓存? [英] How to enable HTTP response caching in the DownloadManager?
问题描述
我希望重复请求从本地缓存提供URL,而不是从服务器重新下载.我正在使用 DownloadManager ,希望它会很方便替代 HttpURLConnection
(看到它的建议),但是默认情况下它不进行响应缓存.这是我的测试代码:
I want repeat requests for a URL to be served from a local cache, not re-downloaded from the server. I'm using the DownloadManager, hoping it'll be a convenient alternative to HttpURLConnection
(saw it recommended), but it does no response caching by default. Here's my test code:
final Context context = getContext();
final DownloadManager manager =
Android.ensureSystemService( DownloadManager.class, context );
final DownloadManager.Request req =
new DownloadManager.Request( Uri.parse( BIG_FILE_URL ));
req.setNotificationVisibility( VISIBILITY_HIDDEN ); // hiding from user
context.registerReceiver( new BroadcastReceiver()
{
public void onReceive( final Context context, final Intent intent )
{
context.unregisterReceiver( this ); // one shot for this test
final long id = intent.getLongExtra( EXTRA_DOWNLOAD_ID, -1L );
System.err.println( " --- downloaded id=" + id );
System.err.println( " --- uri=" +
manager.getUriForDownloadedFile(id) );
}
}, new IntentFilter( ACTION_DOWNLOAD_COMPLETE ));
manager.enqueue( req );
运行两次以上测试,我在远程服务器上看到两个 GET
请求(每个请求都有一个 200
响应),并且在本地Android日志中看到以下内容:>
Running the above test twice, I see two GET
requests at the remote server (each with a 200
response) and the following in the local Android log:
20:14:27.574 D/DownloadManager( 1591): [1] Starting
20:14:28.256 D/DownloadManager( 1591): [1] Finished with status SUCCESS
20:14:28.263 W/System.err( 2203): --- downloaded id=1
20:14:28.269 W/System.err( 2203): --- uri=content://downloads/my_downloads/1
20:15:13.904 D/DownloadManager( 1591): [2] Starting
20:15:14.517 D/DownloadManager( 1591): [2] Finished with status SUCCESS
20:15:14.537 W/System.err( 2203): --- downloaded id=2
20:15:14.541 W/System.err( 2203): --- uri=content://downloads/my_downloads/2
因此,它两次下载了 BIG_FILE
并将其存储在两个文件中.相反,我想要响应缓存. DownloadManager
可以进行响应缓存吗?
So it downloaded BIG_FILE
twice and stored it in two files. Instead I want response caching. Can the DownloadManager
do response caching?
PS.看起来像不".因此,我更正了将我带到这里的建议(请参阅修订22 ).
PS. It looks like ‘no’. So I corrected the recommendation that brought me here (see rev 22).
PPS.可以肯定的是,我测试了标准的 HttpResponseCache .尽管它确实为每个 HttpURLConnection
启用了缓存,但它对 DownloadManager
无效.
PPS. To be sure, I tested a standard HttpResponseCache. It has no effect on the DownloadManager
, though it does enable caching by default for each HttpURLConnection
.
推荐答案
DownloadService默认会下载到一个临时目标.没有内置的功能来缓存请求,但是您可以使用
DownloadService downloads to a temporary destination by default. There is no build-in ability to cache requests, however you can query the list of downloads requested before with DownloadManager.query() method.
这篇关于如何在DownloadManager中启用HTTP响应缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!