我有一个WebClient从API中提取一些数据(字符串)。现在,为了我的代码清洁,我想将它放在公共字符串而不是void。
string value = GetToTheWebClient(parameter);
我怎样才能做到这一点? 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 <<<<
}
答案 0 :(得分: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;
}
希望它会有所帮助。