休息数据得到缓存android

时间:2016-03-15 08:25:29

标签: android rest httpurlconnection

我正在使用以下代码从服务器获取数据。在服务器上更新数据时,我从此方法获取旧数据。当我在Web浏览器中使用相同的方法时,我会获得更新的数据。

即使我停止应用并重新开始它也反映了旧数据,但是当我使用任务管理器清理了所有任务时,我获得了新数据。

数据是否在设备上缓存,因为我每次都在发出新请求

String response = null;
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {

    URL url = new URL(urlString);
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);

    if (method == POST) {
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        OutputStream os = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(params);
        writer.flush();
        writer.close();
        os.close();
    } else {
        urlConnection.setRequestMethod("GET");
    }

    int statusCode = urlConnection.getResponseCode();

    /* 200 represents HTTP OK */
    if (statusCode == HttpURLConnection.HTTP_OK) {
        inputStream = new BufferedInputStream(urlConnection.getInputStream());
        response = convertInputStreamToString(inputStream);
        return response;
    }

我搜索了网页,发现默认情况下使用缓存已启用,因此这两行可能会有所帮助

    urlConnection.setUseCaches(false);
    urlConnection.addRequestProperty("Cache-Control", "no-cache");

1 个答案:

答案 0 :(得分:1)

将一些随机参数(即当前时间戳)附加到URL,然后它将视为新请求。

更改此

URL url = new URL(urlString);

URL url = new URL(urlString+new Date().getTime());