【问题标题】:How to enable HTTP response caching in the DownloadManager?如何在 DownloadManager 中启用 HTTP 响应缓存?
【发布时间】:2016-02-04 03:01:49
【问题描述】:

我希望重复请求从本地缓存提供 URL,而不是从服务器重新下载。我正在使用DownloadManager,希望它可以方便地替代HttpURLConnection (saw it recommended),但默认情况下它没有响应缓存。这是我的测试代码:

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 日志中显示以下内容:

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 可以做响应缓存吗?


PS。它看起来像“不”。所以我更正了将我带到这里的建议 (see rev 22)。

PPS。可以肯定的是,我测试了一个标准的HttpResponseCache。它对DownloadManager 没有影响,尽管它默认为每个HttpURLConnection 启用缓存。

【问题讨论】:

    标签: android


    【解决方案1】:

    DownloadService 默认下载到一个临时目的地。没有内置缓存请求的功能,但是您可以使用DownloadManager.query() 方法查询之前请求的下载列表。

    【讨论】:

    • 缓存涉及到 HTTP 协议。查询工具不会给我那种协调。我无法在框外添加适当的缓存。 (我应该知道,我什至比看看像DownloadManager这样的大盒子方便。它总是被证明是浪费时间。)
    猜你喜欢
    • 2014-08-01
    • 2011-04-21
    • 2011-03-25
    • 2012-08-01
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多