JSON being cached by android application

2019-05-25 18:04发布

I'm currently having an issue with my android application where if I run the app, with the server online, and then close the app with the back button, and turn the server off and then start the app again, the json response is remembered. If I force quit the app, and with the server off run it again, then there is no json response. Where is this response being cached? I am calling it through an instance method to receive this response and I do not understand why this is happening. How can I have my app not remember this response?

In my Activity:

    uFunctions = new JSONFunctions();
    JSONObject json = null;
    System.out.println(json); // Returns null
    json = uFunctions.getJson(uid);
    System.out.println(json); //Returns the json after the request was completed
    //successfully even if the server is offline afterwards.

JSONFunctions:

public class JSONFunctions{

    public JSONFunctions(){
        jParser = new jParser();
    }

    public JSONObject getJson(String uid){
        List<NameValuePair> param = new ArrayList<NameValuePair>();
        param.add(new BasicNameValuePair("tag", "request");
        param.add(new BasicNameValuePair("id", uid);
        JSONObject json = jParser.getJsonFromUrl(url, param);
        return json;
    }
}

jParser:

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);            
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

3条回答
我命由我不由天
2楼-- · 2019-05-25 18:28

I had a similar problem with you. I had a RESTful web service for my android application which is outputting a JSON string via HTTP request. The JSON output is being cached by my android application. In my case:

  1. Request to web service being made and a JSON string is received successfully.
  2. I turned off the web service.
  3. Another same request to web service as no.1 is made for the 2nd time to the web service. This time the requested JSON string must not being returned by the web service. So the android application will show an error in parsing JSON string. But the android httpClient returns the previous JSON string obviously. So, I think this must be some caching problem.

I had solved my problem by 2 step:

  1. Clear all application cached data from Android Settings | Apps menu
  2. Send the following header on web service scripts BEFORE any output:

    Cache-Control: no-cache, must-revalidate -- no caching header
    Expires: Sat, 26 Jul 1997 05:00:00 GMT -- expires in date in the past

    in my case it was written in PHP code like the following:

    <?php
    header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
    ?>

查看更多
疯言疯语
3楼-- · 2019-05-25 18:29

HTTP responses are cached in the system; as Jayp has pointed out, the back button doesn't necessarily flush your app from memory, so the cached response is still there.

If you're using the Apache library, disable caching in your http request object:

  request.setHeader("Cache-Control", "no-cache");

That should do the trick. I think for java.net, you would disable caching in URLConnection:

  conn.setUseCaches(false);

but I haven't actually tried it yet.

查看更多
The star\"
4楼-- · 2019-05-25 18:33

If you quit the app with back button, the system merely puts your app in the background. Therefore, the values allocated to memory on onCreate are remembered and app continues to execute from onResume.

However, if you force quit the app, it is destroyed and all its activities removed from the activity stack. In this scenario the JSON response is also removed and as the server is offline it cannot get any response from there when the app is started again and onCreate called.

Documentation about the activity's lifecycle. Activity documentation

查看更多
登录 后发表回答