java - HttpURLConnection 保持缓存

标签 java android caching httpclient httpurlconnection

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

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();
    }

}

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

最佳答案

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

getDefaultUseCaches(); //or
getUseCaches();

如图所示here in the documentation.

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

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

如图所示 here.

关于java - HttpURLConnection 保持缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31843955/

相关文章:

ruby-on-rails - Heroku上的Rails 4 + Memcached

Java mouseClicked() Canvas 不更新

java - 所有功能文件均未执行

android-layout - 以编程方式遵循 XML 的 Android TextView

Android - ListView - 按需调用 getView()

asp.net - 如何避免在 asp.net mvc 中缓存用户控件?

asp.net - 将网站部署到Azure : Each time requires cleaning the cached content to see the updated website [ASP. NET + REACT]

java - 不使用聚合函数删除sql中的重复项

java - 查找区间交集的算法

javascript - PermissionsAndroid 未显示在 React Native 应用程序中