当我更新服务器上的JSON文件时,Android设备没有获取更新的文件,但是模拟器工作正常,模拟器正在从服务器获取并显示更新的文件。有没有办法通过代码刷新json文件,或者删除服务器缓存中的文件。
AsynTask用于从网络服务器获取视频网址。
private class fetchVideoUrls extends AsyncTask<String, String, List<VideoModel>> {
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
@Override
protected List<VideoModel> doInBackground(String... strings) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(strings[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder buffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String resultJson = buffer.toString();
JSONObject parentObject = new JSONObject(resultJson);
JSONArray parentArray = parentObject.getJSONArray("videos");
List<VideoModel> videoModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
VideoModel videoModel = gson.fromJson(finalObject.toString(), VideoModel.class);
videoModelList.add(videoModel);
}
return videoModelList;
} catch (JSONException | IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(List<VideoModel> result) {
super.onPostExecute(result);
dialog.dismiss();
VideoAdapter adapter = new VideoAdapter(getApplicationContext(), R.layout.video_row, result);
lvVideos.setAdapter(adapter);
}
}
答案 0 :(得分:1)
您是否尝试在openConnection 之前在HttpURLConnection上设置缓存,方法 setUseCaches ?
此方法继承自URLConnection类,如下所述:http://download.java.net/jdk7/archive/b123/docs/api/java/net/HttpURLConnection.html