使用 HttpClient 如何在更改端点的循环中发送 GET 请求和 return 响应

Using HttpClient how can I send GET requests and return a response in a loop that changes the endpoint

感谢您抽出宝贵时间阅读本文。

所以我的目标是通过循环更改 Url 从拥有大量页面的网站中提取一些数据。

例如。

    //want to change part or the url with this array.
    string[] catColors = string[]{"black","brown","orange"}; 

      for (int i = 0; i < catColors.Length; i++){

    string endpoint = $"www.ilovecats.com/color/{catColors[i]}";

      using (HttpClient client = new HttpClient())
                    using (HttpResponseMessage response = await client.GetAsync(endpoint))
                    using (HttpContent content = response.Content)
                    {
                        string data = await content.ReadAsStringAsync();
                        String result = Regex.Replace(data,REGEX,String.Empty);

                        if (data != null)
                        {
                          saveCat.Color = catColors[i].ToString();
                          saveCat.Info = result.Substring(266);
                          catholderList.Add(saveCat);
                        }

//...

发生的只是第一个请求返回正文内容。 其他人正在返回空响应体。

例如

cat1.color = black, cat1.Info ="really cool cat";
cat2.color = brown, cat2.Info =""; // nothing in body
//....same with other 

他们是完成此任务的更好方法吗,因为我不想手动更改 1000 条记录的端点。

saveCat.Color = catColors[i].ToString();
saveCat.Info = result.Substring(266);
catholderList.Add(saveCat);

您在这里只有一个 saveCat 对象。在循环中,您永远不会创建新对象,因此您会不断更改现有对象。而且您还将该单个对象添加到列表中三次。

所以最后,您应该在该列表中得到三个相同的对象。

您应该做的是为每次迭代创建一个新对象:

catholderList.Add(new Cat
{
    Color = catColors[i].ToString(),
    Info = result.Substring(266),
});