【问题标题】:Why does the HttpClient always give me the same response?为什么 HttpClient 总是给我相同的响应?
【发布时间】:2014-02-07 06:34:04
【问题描述】:

环境:
VS2012 更新 4
Windows Phone 8 SDK
基于 WP OS 7.1 的全新 Windows Phone 项目
NuGet 包 1:MS 异步
NuGet 包 2:MS HttpClient


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


用户界面是什么意思

第一个文本块:
响应 json 将显示在此处

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

线程信息:
您刚刚发布的主题使用 [New Post] 按钮


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


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


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

2.但是在Chrome(桌面)打开url,你会发现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;
}

【问题讨论】:

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


    【解决方案1】:

    看来,您在每次刷新点击时都点击了相同的 URL。有时 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();
        }
    

    【讨论】:

    • 非常感谢!请删除url字符串中的API地址,谢谢:)
    • @AlbertGao。我已经删除了 api 地址。现在工作正常吗?
    猜你喜欢
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 2017-01-02
    相关资源
    最近更新 更多