【问题标题】:HTTP response being cached in Android client缓存在 Android 客户端中的 HTTP 响应
【发布时间】:2015-02-17 14:46:26
【问题描述】:

我有以下情况:

  1. 向我的远程服务器发送 http post(post 数据包含 json 字符串)请求。
  2. 从我的服务器以 json 格式获取 http post 响应:{"result":true}
  3. 断开平板电脑中的所有互联网连接。
  4. 重复步骤 1 中描述的发布请求。
  5. 获得相同的缓存“响应” - {“result”:true},这是我没想到的...我不希望我的 http 客户端缓存任何数据。我希望得到 null 或类似的东西。

如何防止http客户端缓存数据?

我的服务处理程序如下所示:

public String makeServiceCall(String url, int method,
        List<NameValuePair> params, String requestAction) {
    try {      

        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);

            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }
            httpResponse = httpClient.execute(httpPost);
        }

        else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);
        }

        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
       // Toast.makeText(Globals.getContext(), "check your connection", Toast.LENGTH_SHORT).show();
    }        
    return response;

}

【问题讨论】:

  • 发布响应并不意味着被缓存。你是如何断定响应被缓存的?
  • 我正在检查 logcat 日志。当我断开互联网并尝试发出请求时 - 我看到以前的响应值(当互联网仍在工作时)而不是 null 或类似的东西。
  • 啊!我刚刚注意到response 是一个成员变量。为什么需要一个成员变量来返回这个结果。您可能在第二次尝试时返回相同的结果。重新抛出您捕获的异常并让调用者处理它。让我知道这是否能解决问题。
  • 感谢您的提示!我解决了我的问题。异常之一是抛出,因此我返回“旧”响应值。将返回值设为 null 并在异常处理程序上方添加额外的返回行解决了我的问题。
  • 不客气。我已将答案从评论部分移至答案部分。

标签: java android json apache http


【解决方案1】:

我刚刚注意到response 是一个成员变量。为什么需要一个成员变量来返回这个结果。您可能在第二次尝试时返回相同的结果。重新抛出您捕获的异常并让调用者处理它。

【讨论】:

    猜你喜欢
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 2011-01-26
    • 2016-04-10
    • 2015-05-21
    相关资源
    最近更新 更多