HTTPClient每次返回相同的字符串

有人可以让我清楚为什么我的代码每次返回相同的字符串?

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秒钟我就得到第一个请求中的相同字符串。 我究竟做错了什么?

这是因为你正在对同一个URL进行GET。 根据HTTP语义,值应该在合理的时间范围内相同,因此操作系统会为您缓存响应。

您可以通过以下任何方法绕过缓存:

  • 使用POST请求。
  • 添加每个调用不同的查询字符串参数。
  • 指定(在服务器上)禁用或限制允许的缓存的响应标头。

如果您使用的是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标头。