HttpURLConnection 保持缓存

HttpURLConnection keeping cache

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

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.