代码之家  ›  专栏  ›  技术社区  ›  Mohamoud Mohamed

使用HttpClient,如何在更改端点的循环中发送GET请求并返回响应

  •  0
  • Mohamoud Mohamed  · 技术社区  · 7 年前

    谢谢你抽出时间来读这个。

    所以我的目标是通过改变一个循环中的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的记录。

    1 回复  |  直到 7 年前
        1
  •  3
  •   poke    7 年前
    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),
    });
    
    推荐文章