HttpURLConnection保持缓存

Env*_*nve 6 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();
    }

}
Run Code Online (Sandbox Code Playgroud)

但看起来它保持缓存,也许不是我不确定,但如果我更改服务器上的数据并重新打开活动,它仍然在应用程序上保持不变.我以前一直在使用HttpClient它,但是因为API 22我把它改成了它所以已经弃用了HttpURLConnection.那有什么方法可以解决这个问题吗?

Geo*_*rge 7

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

getDefaultUseCaches(); //or
getUseCaches();
Run Code Online (Sandbox Code Playgroud)

正如文档中所示.

如果您发现问题所在,那么您只需使用即可更改

setDefaultUseCaches(boolean newValue) //or
setUseCaches(boolean newValue) // Uses a flag (see documentation)
Run Code Online (Sandbox Code Playgroud)

如此处所见.