c# - 将 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; }
}
}
解决方案
你应该这样做:
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 块内进行一些异常处理以防止错误。
推荐阅读
- reactjs - react-leaflet 入门问题
- ffmpeg - 使用 mpegtsmux 和 gstreamer 将 id3 标签注入 mpegts
- c++ - C原始套接字HTTP请求总是返回状态400
- database - 连接错误:SQLSTATE[HY000] [2002] cakephp 烘焙模型和模板
- mongodb - 组文档mongodb
- selenium - Beautiful Soup - 从所有人那里获取文本
- 中的元素
- 中的元素
- javascript - ejs模板引擎上下文中转义和非转义值的含义?
- css - 如何让我的 CSS @media 代码在移动设备上运行以使我的网站具有响应性?
- javascript - 在 Bing Maps API 中绘制一个包含所有给定坐标的圆
- c - gcc 不自动向量化矩阵向量乘法