Java HttpUrl连接保持缓存
我目前正在使用此代码从服务器获取数据Java HttpUrl连接保持缓存,java,android,caching,httpclient,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 =
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
。那么有什么方法可以解决这个问题吗?您可以使用以下命令查看默认情况下是否激活了缓存选项:
getDefaultUseCaches(); //or
getUseCaches();
如所见
如果你发现了你的问题,那么你可以使用
setDefaultUseCaches(boolean newValue) //or
setUseCaches(boolean newValue) // Uses a flag (see documentation)
如图所示,context.getCacheDir()中是否包含任何内容?不,我从未使用过。所谓“重新打开”,是指转到正在运行的应用程序并从那里重新打开,还是指关闭应用程序并再次打开?我指的是关闭活动并再次打开。但我也尝试过关闭整个应用程序并再次打开它。我找到了解决方案。打开连接后,我必须添加
httpconn.setUseCaches(false)
。