如何在 android 中存储 json 数据以供离线使用
How to store json data in android for the purpose of offline
我的应用程序从服务器获取 JSON 数据。如果我使用 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),数据也会在离线状态下显示 ,一旦应用程序连接到互联网。
同样的代码,一个json url在断网后也加载,另一个在断网后数据不显示。如何从服务器端将数据存储在 android 缓存中,如 URL (https://pixabay.com/api/?key=5303976-fd6581ad4ac165d1b75cc15b3&q=kitten&image_type=photo&pretty=true)。
我的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);
?>
我的第一个建议是不要发布您的 API 密钥。 Pixabay可能是免费的,但在互联网上共享 API 密钥会使您的基础设施处于危险之中。
查找请求后,似乎 Pixabay 正在设置一些 headers 可能会影响您的缓存。
Access-Control-Max-Age → 86400
Cache-Control → max-age=86400
Content-Type → application/json
查看有关 HttpResponseCache 的 Android 文档,其中概述了如何在设置 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
}
我的应用程序从服务器获取 JSON 数据。如果我使用 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),数据也会在离线状态下显示 ,一旦应用程序连接到互联网。
同样的代码,一个json url在断网后也加载,另一个在断网后数据不显示。如何从服务器端将数据存储在 android 缓存中,如 URL (https://pixabay.com/api/?key=5303976-fd6581ad4ac165d1b75cc15b3&q=kitten&image_type=photo&pretty=true)。
我的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);
?>
我的第一个建议是不要发布您的 API 密钥。 Pixabay可能是免费的,但在互联网上共享 API 密钥会使您的基础设施处于危险之中。
查找请求后,似乎 Pixabay 正在设置一些 headers 可能会影响您的缓存。
Access-Control-Max-Age → 86400
Cache-Control → max-age=86400
Content-Type → application/json
查看有关 HttpResponseCache 的 Android 文档,其中概述了如何在设置 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
}