首页 > 解决方案 > 将 WebClient 代码转换为 HttpClient 代码

问题描述

如果可能的话,我需要帮助将此 WebClient 转换为 HttpClient 代码,如果可以,我会非常高兴。

我一直在寻找可以将其转换为我的东西/某人,但遗憾的是我什么也没找到。

谢谢!

    private void bunifuFlatButton9_Click(object sender, EventArgs e)
    {
        {
            using (WebClient webClient = new WebClient())
            {
                webClient.Encoding = Encoding.UTF8;
                webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(this.Complete);
                webClient.DownloadDataAsync(new Uri("https://www.bing.com/search?q=site:pastebin.com+" + this.textBox1.Text));
                webClient.DownloadDataAsync(new Uri("https://www.bing.com/search?q=site:pastebin.com+" + this.textBox1.Text));
                webClient.DownloadDataAsync(new Uri("https://duckduckgo.com/?q=site%3Apastebin.com+" + this.textBox1.Text));
                webClient.DownloadDataAsync(new Uri("https://duckduckgo.com/?q=site%3Apastebin.com+" + this.textBox1.Text));
                webClient.DownloadDataAsync(new Uri("https://duckduckgo.com/?q=site%3Apastebin.com+" + this.textBox1.Text));
                webClient.DownloadDataAsync(new Uri("https://yandex.ru/search/?text=" + this.textBox1.Text));
                webClient.DownloadDataAsync(new Uri("https://yandex.ru/search/?text=" + this.textBox1.Text));
                webClient.DownloadDataAsync(new Uri("https://yandex.ru/search/?text=" + this.textBox1.Text));
                webClient.DownloadDataAsync(new Uri("https://yandex.ru/search/?text=" + this.textBox1.Text));
                webClient.DownloadDataAsync(new Uri("https://yandex.ru/search/?text=" + this.textBox1.Text));

            }
        }
    }

    private void Complete(object sender, DownloadDataCompletedEventArgs e)
    {
        MatchCollection matchCollection = Regex.Matches(new UTF8Encoding().GetString(e.Result), "(https:\\/\\/pastebin.com\\/\\w+)");
        int num = checked(matchCollection.Count - 1);
        int i = 0;
        while (i <= num)
        {
            using (WebClient webClient = new WebClient())
            {
                webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(this.Complete2);
                webClient.DownloadStringAsync(new Uri(matchCollection[i].Value));
            }
            checked { ++i; }
        }
    } 

标签: c#httpclientwebclient

解决方案


你应该这样做:

HttpClient client = new HttpClient();
List<string> urls = new List<string>();
urls.Add("https://www.bing.com/search?q=site:pastebin.com+" + this.textBox1.Text);
urls.Add("https://www.bing.com/search?q=site:pastebin.com+" + this.textBox1.Text);
//and so on...
foreach(var url in urls)
{
   client.GetAsync(url)
           .ContinueWith(async (T) => {
                 string result = await T.Result.ReadAsStringAsync();
                 OnComplete(result);
            });
}

然后:

public void OnComplete(string result)
{
  //todo: convert your result to utf-8 and so on...
}

您可以在 ContinueWith 块内进行一些异常处理以防止错误。


推荐阅读