有人可以让我弄清楚为什么我的代码每次都返回相同的字符串吗?
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语义,该值应在合理的时间范围内相同,因此OS会为您缓存响应。
您可以通过以下任何一种方法绕过缓存:
如果使用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
标头。
我尽了一切,这对我有用。以防万一有些无法正常工作:
var uri = new Uri("http://192.168.4.160:8081/v?time=" + DateTime.Now);