将 WebClient 代码转换为 HttpClient 代码

Converting WebClient code to HttpClient code

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

我一直在寻找 something/someone 可以将其转换给我,遗憾的是我没有找到任何东西。

谢谢!

    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; }
        }
    } 

你应该这样做:

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 块中进行一些异常处理以防止错误。