首页 > 解决方案 > 使用 HttpClient 如何发送 GET 请求并在更改端点的循环中返回响应

问题描述

感谢您抽出时间来阅读。

所以我的目标是通过循环更改 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 条记录。

标签: c#asp.net-core-2.0dotnet-httpclient

解决方案


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

推荐阅读