Search code examples
c#wpfwindows-store-apps

HTTPClient every time returns the same string


Could some one make me clear why my code returns the same string every time?

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;

So every 5 seconds I get the same string that I got in my first request. What am I doing wrong?


Solution

  • It's because you're doing a GET to the same URL. According to the HTTP semantics, the value should be the same within a reasonable timeframe, so the OS is caching the response for you.

    You can bypass the cache by any of these methods:

    • Using a POST request.
    • Adding a query string parameter that is different for each call.
    • Specifying (on the server) response headers that disable or limit the caching allowed.