【问题标题】:HttpURLConnection keeping cacheHttpURLConnection 保持缓存
【发布时间】:2015-08-05 22:35:36
【问题描述】:

我目前正在使用此代码从服务器获取数据

public static String getResponse(String URL) throws IOException{

    try{
        String response_string;
        StringBuilder response  = new StringBuilder();
        URL url = new URL(URL);
        HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();

        if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK){
            BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()));
            String strLine = null;
            while ((strLine = input.readLine()) != null){
                response.append(strLine);
            }
            input.close();
            response_string = response.toString();
        }

        httpconn.disconnect();

        return response_string;
    }
    catch(Exception e){
        throw new IOException();
    }

}

但看起来它正在保留缓存,也许不是我不确定,但如果我更改服务器上的数据并重新打开活动,它在应用程序上仍然保持不变。我一直在使用HttpClient,之前它运行良好,但因为自API 22 以来它已被弃用,我将其更改为HttpURLConnection。那么有没有办法解决这个问题呢?

【问题讨论】:

  • context.getCacheDir() 里面有什么吗?
  • 不,我从未使用过。
  • “重新打开”是指转到正在运行的应用程序并从那里重新打开,还是您的意思是关闭应用程序并再次打开?
  • 我的意思是关闭活动并再次打开它。但我也尝试关闭整个应用程序并再次打开它。
  • 我找到了解决方案。我只需要在打开连接后添加httpconn.setUseCaches(false)

标签: java android caching httpclient httpurlconnection


【解决方案1】:

您可以使用以下命令查看默认情况下是否激活了缓存选项:

getDefaultUseCaches(); //or
getUseCaches();

如所见here in the documentation.

如果你发现你的问题,那么你可以简单地改变它使用

setDefaultUseCaches(boolean newValue) //or
setUseCaches(boolean newValue) // Uses a flag (see documentation)

here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 2011-12-25
    • 2021-05-18
    相关资源
    最近更新 更多