Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are using Windows.Web.Http.HttpClient, you can skip the local cache this way:

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();

You will never get the same response twice again :)

But if you have access to the server source code, the most elegant fix would be to disable the cache for the URI you are downloading, i.e., add the Cache-Control: no-cache header.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...