【问题标题】:HTTPClient every time returns the same stringHTTPClient 每次都返回相同的字符串
【发布时间】:2019-10-01 11:41:12
【问题描述】:

谁能告诉我为什么我的代码每次都返回相同的字符串?

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 秒我都会收到与第一个请求中相同的字符串。 我做错了什么?

【问题讨论】:

  • 您实际上并没有等到得到数据才显示它。您最好将getData() 方法设为异步Task<string> 方法,然后您的计时器滴答处理程序也可以是异步的,主体为HubText.Text = await getData();。目前,我希望您看到下一个值晚了 5 秒。但是由于您没有告诉我们任何有关该 URL 的返回内容的信息,我们不知道它为什么会改变。
  • 我发现了另一种方法:使用 System.Net.Http 对抗 Windows.Net.Http;

标签: c# wpf windows-store-apps


【解决方案1】:

如果你使用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 标头。

【讨论】:

【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    我尝试了一切,这个对我有用。以防万一有些人无法使其工作:

    var uri = new Uri("http://192.168.4.160:8081/v?time=" + DateTime.Now);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-09
      • 2020-01-28
      • 2020-09-30
      • 2016-01-24
      • 2012-05-28
      相关资源
      最近更新 更多