为什么HttpClient总是给我相同的响应?

时间:2014-02-07 06:34:04

标签: c# windows-phone-7 asynchronous nuget dotnet-httpclient

环境:
VS2012 Update 4
Windows Phone 8 SDK
基于WP OS 7.1的全新Windows Phone项目 NuGet pack1:MS Async
NuGet pack2:MS HttpClient

项目做什么
论坛API的单一测试:
在论坛中发布新主题并刷新JSON以检查“计数”是否累积。


用户界面意味着什么
enter image description here
第一个文本块:
响应json将在这里显示

3个按钮:
[刷新JSON]:使用API​​1刷新线程列表
[新帖]:使用API​​2在论坛中发布新帖子,标题和文字将显示在下方 [IE]:在IE中打开json使用API​​1

线程信息:
您刚刚发布的帖子使用[新帖子]按钮

JSON意味着什么
只需要关注2个部分
数:244 --->论坛中的总线程数 “57923”--->第一个线程的标题(字段“data”是线程列表的数组)


什么是测试程序
1.打开应用程序
2.单击[刷新JSON]以获取列表
3.记住第一个线程的“计数”部分和“标题” 4.单击[新发布]发布新主题,主题标题将显示在下方
5.单击[刷新JSON]以查看最新的线程列表
6.预期:“计数”累计1,“标题”部分应与下列相同


问题:
1.点击[新帖子]后,无论你点击[刷新JSON]多少次,计数都不会累积!

2.但是打开Chrome(桌面)中的网址,您会发现JSON已经更新了!

3.关闭应用程序并重新打开它,点击[刷新JSON],JSON将按预期更新,但是当你发布一个新线程时,问题再次出现


为什么以及如何解决?

代码

private async void RefreshJSONButton_Click(object sender, RoutedEventArgs e)
{
    this.JsonView.Text = string.Empty;
    HttpClient client = new HttpClient();
    string url =
        "API1 Address Here";
    string x = await client.GetStringAsync(url);
    this.JsonView.Text = x;
    client.Dispose();
}

private async void NewPostButton_Click_1(object sender, RoutedEventArgs e)
{
    Random rnd = new Random();
    this.num = rnd.Next(1, 99999);

    // generate the title and content with random number
    string threadTitle = this.num.ToString();
    string threadContent = "111" + num.ToString();

    // generate the url
    string url =
        "API2 Address Here";
    url = url + "&title=" + threadTitle + "&content=" + threadContent;

    // use HttpClient to send the new thread
    HttpClient client = new HttpClient();
    string x = await client.GetStringAsync(url);
    client.Dispose();

    // display the thread informartion for further check
    this.titleView.Text = threadTitle;
    this.contentView.Text = threadContent;
}

1 个答案:

答案 0 :(得分:4)

看来,您在每次刷新点击时都会遇到相同的网址。有时Windows Phone将请求和响应存储在缓存中。

如果可能,您还需要在请求中添加一个参数,并且每次单击都只需更改此参数的值。您可以使用GUID或Unix时间戳。

您可以尝试:

 private async void RefreshJSONButton_Click(object sender, RoutedEventArgs e)
    {
        this.JsonView.Text = string.Empty;
        HttpClient client = new HttpClient();
    int unixTimestamp = (int)(DateTime.Now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

    string url =
    "http://API1 Address Here/Your queries&temp=unixTimestamp";
    string x = await client.GetStringAsync(url);
    this.JsonView.Text = x;
    client.Dispose();
    }