[英]Using HttpClient how can I send GET requests and return a response in a loop that changes the endpoint
Thank you for taking the time to read this. 感谢您抽出时间来阅读。
So my goal is to pull some data from a website that has tons of pages by changing the Url in a loop. 因此,我的目标是通过循环更改网址来从具有大量页面的网站中提取一些数据。
ex. 恩。
//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);
}
//... // ...
What is happening is only the first request is returning the body content. 发生的事情只是第一个请求返回了正文内容。 the others are returning empty response bodies.
其他的则返回空的响应主体。
for ex. 对于前。
cat1.color = black, cat1.Info ="really cool cat";
cat2.color = brown, cat2.Info =""; // nothing in body
//....same with other
Is their a better way of accomplishing this as I dont want to change the endpoint manually for 1000s of records. 他们是实现此目标的更好方法,因为我不想为1000条记录手动更改端点。
saveCat.Color = catColors[i].ToString();
saveCat.Info = result.Substring(266);
catholderList.Add(saveCat);
You only have a single saveCat
object here. 您在这里只有一个
saveCat
对象。 Within your loop, you never create a new object, so you keep changing the existing object. 在循环中,您永远不会创建新对象,因此您会不断更改现有对象。 And you also add that single object to the list three times.
然后,您还将单个对象添加到列表中三次。
So in the end, you should end up with three identical objects inside of that list. 因此,最后,您应该在该列表内包含三个相同的对象。
What you should do instead is create a new object for every iteration: 相反,您应该为每次迭代创建一个新对象:
catholderList.Add(new Cat
{
Color = catColors[i].ToString(),
Info = result.Substring(266),
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.