c# - 使用 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 条记录。
解决方案
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),
});
推荐阅读
- android - 某些手机中未显示 Toast 通知
- python - 多重继承:第二个基类构造函数要求泄漏到第一个基类构造函数
- jquery - Jquery滚动减少div的比例
- ruby-on-rails - Ruby on Rails 路由部署问题
- mysql - 如何在 sequelize 上创建存储过程
- java - 如何使用 Netty Reactor 关闭 TcpClient 连接?
- c# - 条码 ASP.NET C# 问题
- html - 在 PhpStorm 中选择标签。我想在 PhpStorm 中打开标签,关闭它并将选择器放在中间(就像在 Sublime 中一样)
- php - 是否可以在 MySQL 中的其他记录之间添加记录?
- redis - redis.call 失败