我的应用中遇到HttpClient
的问题。当我在手机上更改日期或时间时,HttpClient
缓存会搞砸。例如,当我向后更改日期并再次运行应用程序时,每个响应都从缓存中获取,当我向前移动日期时,不会缓存任何请求,也不会从缓存中获取任何请求。我不知道问题出在哪里,所以如果遇到类似的问题请帮忙。
有没有办法以编程方式清除HttpClient
缓存?我会在每个应用程序启动时都这样做。
编辑:
我只是使用Fiddler来查看响应并发现'Date'响应头中的时间是正确的时间(在服务器上),并且HttpClient
可能使用此标头进行计算并结合时间设备,返回错误的结果
EDIT2: 一个用例: 当用户打开应用程序并获取缓存控制标头设置为10秒的URL(http://my.website.com/jsondata),然后关闭应用程序并向后或向前更改时间,然后在一段时间内再次打开应用程序,然后在第一种情况下,httpclient始终从其缓存中获取相同URL的响应,在第二种情况下,永远不再使用缓存(如果用户在10秒内多次请求相同的URL)
我的代码是:
public async Task<StringServerResponse> DownloadJsonAsync(Uri uri, DecompressionMethods decompressionMethod = DecompressionMethods.None, int timeout = 30000, int retries = 3)
{
if (retries < 1 || retries > 10) retries = 3;
int currentRetries = 0;
// Baseline delay of 1 second
int baselineDelayMs = 1000;
// Used for exponential back-off
Random random = new Random();
StringServerResponse response = new StringServerResponse();
if (decompressionMethod == DecompressionMethods.GZip)
{
//Use decompression handler
using (var compressedHttpClientHandler = new HttpClientHandler())
{
if (compressedHttpClientHandler.SupportsAutomaticDecompression)
{
compressedHttpClientHandler.AutomaticDecompression = System.Net.DecompressionMethods.GZip;
}
using (var httpClient = new HttpClient(compressedHttpClientHandler))
{
httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);
do
{
++currentRetries;
try
{
var httpResponse = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseContentRead);
if (httpResponse.IsSuccessStatusCode)
{
response.StatusCode = httpResponse.StatusCode;
response.Content = await httpResponse.Content.ReadAsStringAsync();
return response;
}
}
catch (Exception)
{
}
int delayMs = baselineDelayMs + random.Next((int) (baselineDelayMs*0.5), baselineDelayMs);
if (currentRetries < retries)
{
await Task.Delay(delayMs);
DebugLoggingService.Log("Delayed web request " + delayMs + " seconds.");
}
// Increment base-delay time
baselineDelayMs *= 2;
} while (currentRetries < retries);
}
}
}
else
{
// same but without gzip handler
}
return null;
}
答案 0 :(得分:0)
您可以尝试在URL中为输入查询添加一个参数。您可以关注我的另一篇文章:Why does the HttpClient always give me the same response?