有人可以告诉我为什么我的代码每次都返回相同的字符串吗?
public MainPage()
{
this.InitializeComponent();
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(5);
timer.Tick += OnTimerTick;
timer.Start();
}
private void OnTimerTick(object sender, object e)
{
getData();
HubText.Text = dumpstr;
}
private async void getData()
{
// Create an HttpClient instance
HttpClient client = new HttpClient();
var uri = new Uri("http://192.168.4.160:8081/v");
try
{
// Send a request asynchronously continue when complete
HttpResponseMessage response = await client.GetAsync(uri);
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously
dumpstr = await response.Content.ReadAsStringAsync();
}
catch (Exception e)
{
//throw;
}
}
string dumpstr;
所以每隔5秒我就得到第一个请求中的字符串。 我做错了什么?
答案 0 :(得分:15)
如果您使用的是Windows.Web.Http.HttpClient
,则可以通过以下方式跳过本地缓存:
Windows.Web.Http.Filters.HttpBaseProtocolFilter filter =
new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
filter.CacheControl.ReadBehavior =
Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
HttpClient client = new HttpClient(filter);
Uri uri = new Uri("http://example.com");
HttpResponseMessage response = await client.GetAsync(uri);
response.EnsureSuccessStatusCode();
string str = await response.Content.ReadAsStringAsync();
你永远不会再两次得到同样的答案:)
但是,如果您可以访问服务器源代码,那么最优雅的修复方法是禁用正在下载的URI的缓存,即添加Cache-Control: no-cache
标头。
答案 1 :(得分:8)
这是因为你正在对同一个网址进行GET。根据HTTP语义,该值应该在合理的时间范围内相同,因此操作系统会为您缓存响应。
您可以通过以下任何方法绕过缓存:
答案 2 :(得分:0)
我尽了一切,这对我有用。以防万一某些工具无法正常工作:
getFecha()