0

我有一个从 API 获取一些数据(字符串)的 WebClient。现在,为了我的代码整洁,我想把它放在一个公共字符串中而不是 void 中。

字符串值 = GetToTheWebClient(参数);

我怎样才能做到这一点?DownloadStringCompleted 事件处理程序无法返回任何内容。

亲切的问候,尼尔斯

编辑

我添加了一段代码,可以更好地解释它。

string value = GetToTheWebClient(parameter);

public string GetToTheWebClient(parameter)
{
    WebClient client = new WebClient();
    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client     _DownloadStringCompleted);
    client .DownloadStringAsync(new Uri("http://ThatsACoolURLBro" + parameter, UriKind.Absolute));
}

void client _DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
     // Do some fancy XML processing.


     >>>> Return the outcome value back to the GetToTheWebClient - string <<<<
}
4

1 回答 1

0

我已经玩过 Webclient 类。请看下面的例子。请使用这个,如果你

对此方法感到满意。

public string DownloadWebPageData(string url)
    {
        string html = string.Empty;
        try
        {
            using (ConfigurableWebClient client = new ConfigurableWebClient())
            {
                /* Set timeout for webclient */
                client.Timeout = 600000;

                /* Build url */
                Uri innUri = null;
                if (!url.StartsWith("http://"))
                    url = "http://" + url;

                if (url.EndsWith("."))
                    innUri = ManipulateBrokenUrl(url);
                else
                    Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out innUri);

                try
                {
                    client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729) (Prevx 3.0.5)");
                    client.Headers.Add("Vary", "Accept-Encoding");

                    // Specify the encoding for unicode characters
                    client.Encoding = Encoding.UTF8;

                    html = client.DownloadString(innUri);

                    if (string.IsNullOrEmpty(html))
                    {
                        return string.Empty;
                    }
                    else
                    {
                        return html;
                    }

                }
                catch (WebException we)
                {
                    return string.Empty;
                }
                catch (Exception ex)
                {
                    return "";
                }
                finally
                {
                    client.Dispose();
                }
            }
        }
        catch (Exception ex)
        {
            return "";
        }
        return null;
    }

希望会有所帮助。

于 2013-11-13T10:44:09.533 回答