如何在WebClient.DownloadStringAsync中使用字符串URL

25

目前我使用以下代码设置 WebClient 的 URL:

WebClient Detail = new WebClient();
Detail.DownloadStringCompleted += new
    DownloadStringCompletedEventHandler(Detail_DownloadStringCompleted);
Detail.DownloadStringAsync(new Uri("http://api.trademe.co.nz/v1/Listings/" +
    ListingID.Text + ".xml"));

我想要做的是使用这个字符串:

void ListBoxSelectionChanged(object sender, SelectionChangedEventArgs args)
{
    var lbi = ((sender as ListBox).SelectedItem as TradeItem);
    if(lbi != null)
    {
        string id = lbi.ListingId.ToString();
    }
}
作为那个WebClient URL的一部分。
例如:
WebClient Detail = new WebClient();
Detail.DownloadStringCompleted += new
    DownloadStringCompletedEventHandler(Detail_DownloadStringCompleted);
Detail.DownloadStringAsync(new Uri("http://api.trademe.co.nz/v1/Listings/" + id +
    ".xml"));

有没有办法像上面展示的那样在URL中使用这个字符串?

完整代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;

namespace TradeMe_Panorama
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor.
        public MainPage()
        {
            InitializeComponent();
            // Set the data context of the listbox control to the sample data.
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // Load data for the ViewModel items.
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            WebClient Trademe = new WebClient();
            Trademe.DownloadStringCompleted += new   
            DownloadStringCompletedEventHandler(Trademe_DownloadStringCompleted);
            Trademe.DownloadStringAsync(new
            Uri("http://api.trademe.co.nz/v1/Search/General.xml?search_string=" +
            TradeSearch.Text));
            progressBar1.IsIndeterminate = true;
            progressBar1.Visibility = Visibility.Visible;
        }

        // Display listing for used general products:
        void Trademe_DownloadStringCompleted(object sender,
            DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;
            var r = XDocument.Parse(e.Result);
            // Declare the namespace.
            XNamespace ns = "http://api.trademe.co.nz/v1";
            TradeSearch1.ItemsSource = from TM in r.Root.Descendants(ns +
                "Listing").Take(20)
            select new TradeItem
            {
                ImageSource = TM.Element(ns + "PictureHref").Value,
                Title = TM.Element(ns + "Title").Value,
                Region = TM.Element(ns + "Region").Value,
                PriceDisplay = TM.Element(ns + "PriceDisplay").Value,
                ListingId = TM.Element(ns + "ListingId").Value,
            };
            progressBar1.IsIndeterminate = false;
            progressBar1.Visibility = Visibility.Collapsed;
        }

        // Display listing for used Cars.
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            WebClient Motor = new WebClient();
            Motor.DownloadStringCompleted += new
            DownloadStringCompletedEventHandler(Motor_DownloadStringCompleted);
            Motor.DownloadStringAsync(new
            Uri("http://api.trademe.co.nz/v1/Search/Motors/Used.xml?search_string=" +
            MotorSearch.Text));
            progressBar1.IsIndeterminate = true;
            progressBar1.Visibility = Visibility.Visible;
        }        

        void Motor_DownloadStringCompleted(object sender,
            DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;
            var r = XDocument.Parse(e.Result);
            // Declare the namespace.
            XNamespace ns = "http://api.trademe.co.nz/v1";
            MotorsListings.ItemsSource = from M in r.Root.Descendants(ns +
                "Car").Take(20)
            select new TradeItem
            {
                ImageSource = M.Element(ns + "PictureHref").Value,
                Title = M.Element(ns + "Title").Value,
                Region = M.Element(ns + "Region").Value,
                PriceDisplay = M.Element(ns + "PriceDisplay").Value,
                ListingId = M.Element(ns + "ListingId").Value,
            };
            progressBar1.IsIndeterminate = false;
            progressBar1.Visibility = Visibility.Collapsed;
        }

        //Display specific details of listings:
        private void button4_Click(object sender, RoutedEventArgs e)
        {
            WebClient Detail = new WebClient();
            Detail.DownloadStringCompleted += new
            DownloadStringCompletedEventHandler(Detail_DownloadStringCompleted);
            Detail.DownloadStringAsync(new
            Uri("http://api.trademe.co.nz/v1/Listings/" + ListingID.Text +
            ".xml"));
            progressBar1.IsIndeterminate = true;
            progressBar1.Visibility = Visibility.Visible;
        }
        
        void Detail_DownloadStringCompleted(object sender,
            DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;
            var r = XDocument.Parse(e.Result);
            // Declare the namespace.
            XNamespace ns = "http://api.trademe.co.nz/v1";
            ListingDetails.ItemsSource = from D in r.Descendants(ns +
            "ListedItemDetail").Take(20)
            select new TradeItem
            {
                ImageSource = D.Element(ns + "Photos").Element(ns +
                "Photo").Element(ns + "Value").Element(ns + "Medium").Value,
                Title = D.Element(ns + "Title").Value,
                Region = D.Element(ns + "Region").Value,
                PriceDisplay = D.Element(ns + "Body").Value,
                ListingId = D.Element(ns + "ListingId").Value,
                CloseDate = D.Element(ns + "EndDate").Value,
                BuyNow = D.Element(ns + "BuyNowPrice").Value,
                StartPrice = D.Element(ns + "StartPrice").Value,
            };
            progressBar1.IsIndeterminate = false;
            progressBar1.Visibility = Visibility.Collapsed;
        }

        public class TradeItem
        {
            public string Region { get; set; }
            public string ListingId { get; set; }
            public string PriceDisplay { get; set; }
            public string Title { get; set; }
            public string ImageSource { get; set; }
            public string CloseDate { get; set;  }
            public string StartPrice { get; set; }
            public string BuyNow { get; set; }
        }
        // Run query string to pass LIstingID to next page.
    }
}

3
你的问题不够清晰,你面临的问题是什么? - Shekhar_Pro
3个回答

46

另一种方法是使用Task:

using (WebClient client = new WebClient())
{                
    result = await client.DownloadStringTaskAsync(urlString);
}

2
WebClient.DownloadStringAsync 返回的是 void,而不是 Task<string> - João Luiz Grigoletti
6
@JoГЈoLuizGrigolettiиҜ·еҶҚж¬Ўйҳ…иҜ»зӯ”жЎҲпјҢд»–и°ғз”ЁдәҶдёҚеҗҢзҡ„ж–№жі•пјҢиҖҢдё”е®ғе®ҢзҫҺең°иө·дҪңз”ЁдәҶгҖӮ - Boy
2
现在这应该是首选的解决方案。同时也没有注意到有一个“正确”的Task方法。 - Ray

13

这是你需要做的事情:

WebClient wc = new WebClient();
wc.DownloadStringCompleted += new
    DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri("http://api.trademe.co.nz/v1/Listings/" +
    id + ".xml"));

void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    string text = e.Result;
    // … do something with result.
}

在那里,您将拥有自己的文字。


在你的代码中,你完全忽略了异步能力。 - S.H.

11

他们是否达成一致意见?如果是这样,那么您可以将id变量设置为类级别变量,以便可以从类中的任何位置访问它。或者,您可以将WebClient部分放入一个接受字符串的方法中。例如:

private void DownloadInformation(string id)
{
    WebClient Detail = new WebClient();
    Detail.DownloadStringCompleted += new        DownloadStringCompletedEventHandler(Detail_DownloadStringCompleted);
    Detail.DownloadStringAsync(new Uri("http://api.trademe.co.nz/v1/Listings/" + id + ".xml"));
}

然后在 ListboxSelectionChanged 处理程序中,只需调用上述方法即可。

if(lbi != null)
{
    string id = lbi.ListingId.ToString();
    DownloadInformation(id);
}

另外需要注意的是,最好将WebClient设置在方法之外,比如在页面的Loaded事件中。这样,每次都不需要创建一个新实例。


那似乎对我不起作用。我会更新所有的代码,也许你可以向我展示应该如何实现。 - Rhys
同时,是的,它们在同一页上 - 这是一个全景页面。 - Rhys
没有错误,但是我没有得到结果。之前我有一个按钮点击来执行方法。现在如果我点击堆栈面板中列出的结果,什么也不会发生。 - Rhys

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接