windows phone 8.1 中 HttpClient.GetStringAsync 方法的问题

Issue with HttpClient.GetStringAsync method in windows phone 8.1

private async void refresh_Tapped(object sender, TappedRoutedEventArgs e)
{
    httpclient.CancelPendingRequests();
    string url = "http://gensav.altervista.org/";
    var source = await httpclient.GetStringAsync(url); //PROBLEM
    source = WebUtility.HtmlDecode(source);
    HtmlDocument result = new HtmlDocument();
    result.LoadHtml(source);

    List<HtmlNode> toftitle = result.DocumentNode.Descendants().Where
                                (x => (x.Attributes["style"] != null
                                       && x.Attributes["style"].Value.Contains("font-size:14px;line-height:20px;margin-bottom:10px;"))).ToList();

    var li = toftitle[0].InnerHtml.Replace("<br>", "\n");
    li = li.Replace("<span style=\"text-transform: uppercase\">", "");
    li = li.Replace("</span>", "");
    postTextBlock.Text = li;
}

这段代码的作用基本上是从网站中检索一个字符串(HTML 源代码,之后立即进行解析)。每当我单击一个按钮时都会执行此代码:第一次单击它时它可以正常工作,但第二次我认为该方法 (GetStringAsync) returns 是一个未完成的任务,然后使用 [ 的旧值继续执行=18=]来源。事实上,我的 TextBlock 没有更新。

有什么解决办法吗?

您可能会收到缓存的响应。

希望这对你有用:

httpclient.CancelPendingRequests();

// disable caching
httpclient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");

string url = "http://gensav.altervista.org/";
var source = await httpclient.GetStringAsync(url);
...

您还可以像这样向 url 添加无意义的值:

 string url = "http://gensav.altervista.org/" + "?nocahce=" + Guid.NewGuid();

为了防止缓存 Http 响应,我这样做(在 WP8.1 中):

HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
filter.CacheControl.ReadBehavior =
            Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
filter.CacheControl.WriteBehavior =
            Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;

_httpClient = new HttpClient(filter);

以这种方式初始化您的 HttpClient 以防止缓存行为。