WebClient.DownloadStringAsync webexception wp7

时间:2013-06-07 08:13:58

标签: windows-phone-7 webexception

我正在尝试从xml文件中删除一个节点,一切正常,但有时会发生xml网页无法加载。这是我的代码:

private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error == null)
        {
            XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
            if (e.Error == null)
            {
                XDocument doc = XDocument.Parse(e.Result, LoadOptions.None);

                    var lyric = doc.Descendants(XName.Get("Lyric", "http://api.chartlyrics.com/")).FirstOrDefault();
                    TextBlock1.Text = lyric.Value;


            }

        }
    }

    private void btnLoad_Click(object sender, RoutedEventArgs e)
    {



        WebClient wc = new WebClient();
        wc.DownloadStringCompleted += HttpsCompleted;
        wc.DownloadStringAsync(new Uri("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad));


    }

我已阅读过使用WebException来处理这个“错误”,但我无法使用它。有人可以给我一些帮助吗?

1 个答案:

答案 0 :(得分:1)

你试过这种方式吗?

    private void btnLoad_Click(object sender, RoutedEventArgs e)
    {
        try
        {

            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += HttpsCompleted;
            wc.DownloadStringAsync(new Uri("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad"));
        }
        catch (WebException ex)
        {
            // Check the exception here
        }
    }

并检查处理程序中的错误:

private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error == null)
    {
        XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
        if (e.Error == null)
        {
            XDocument doc = XDocument.Parse(e.Result, LoadOptions.None);

                var lyric = doc.Descendants(XName.Get("Lyric", "http://api.chartlyrics.com/")).FirstOrDefault();
                TextBlock1.Text = lyric.Value;
        }       
    }
    else
    {
        // Check for error here
    }
}

我意识到它有时会返回Error,我认为问题出在服务器上,因为如果我从Web浏览器访问它,我有时会得到结果,但很多时候我都会收到错误。