douliao8402 2018-03-07 15:46
浏览 517
已采纳

如何在android中存储json数据以便离线

My application get JSON data from server. If I use my own json api , data is loaded only in internet connection. But if I use this api (https://pixabay.com/api/?key=5303976-fd6581ad4ac165d1b75cc15b3&q=kitten&image_type=photo&pretty=true), data is displayed also in offline, once application got internet connection.

The same code, one json url is loaded also after the loss of internet connectivity, another one's data doesn't display after internet disconnection. How to store data in android cache from server-side as this URL (https://pixabay.com/api/?key=5303976-fd6581ad4ac165d1b75cc15b3&q=kitten&image_type=photo&pretty=true).

My api (api1.php)

<?php 
    require("includes/connect.php");
header('Content-Type: application/json');

    $query="SELECT * FROM implink";
$result = $con->query('SELECT id,heading,content FROM implink');
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json;charset=utf-8');
echo json_encode(['info' => $rows],
        JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
?> 
  • 写回答

1条回答 默认 最新

  • dongrendang6566 2018-03-07 16:17
    关注

    My first suggestion is to not publish your API key. Pixabay may be free, but sharing API keys on the internet will put you infrastructure in danger.

    Upon looking up the request it seems Pixabay is setting some headers that could affect your cache.

    Access-Control-Max-Age → 86400
    Cache-Control → max-age=86400
    Content-Type → application/json
    

    Check out the Android documentation on HttpResponseCache It outlines how you can force a cache response after setting up the HttpResponseCache.

         try {
             connection.addRequestProperty("Cache-Control", "only-if-cached");
             InputStream cached = connection.getInputStream();
             // the resource was cached! show it
         } catch (FileNotFoundException e) {
             // the resource was not cached
         }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来