Windows Phone 8.1中的HttpClient.GetStringAsync方法问题

时间:2015-04-16 09:30:49

标签: windows windows-phone-8 windows-phone windows-phone-8.1 dotnet-httpclient

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)返回一个未完成的任务,然后使用 source <的旧值继续执行/ strong>即可。实际上,我的TextBlock不会更新。

任何解决方案?

2 个答案:

答案 0 :(得分:2)

你可能得到一个缓存的回复。

愿这对您有用:     

httpclient.CancelPendingRequests();

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

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

您还可以在网址中添加无意义的值,如下所示:

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

答案 1 :(得分:0)

为了防止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以防止缓存行为。