My code works, however, because I am using a public API, I'm limited to 100 requests at a time.
Currently I am using a foreach loop to execute a request. The code looks like this.
public static List<string> keyList = new List<string>();
public static string Uri1 = "api url address";
public static string URLreq;
public static List<string> reqs = new List<string>();
static void apiReq()
{
string filePath = "Path To File\\a.txt";
var fileLines = System.IO.File.ReadAllLines(filePath);
foreach(string s in fileLines)
{
keyList.Add(s);
}
for (int ab = 0; ab < keyList.Count; ab++)
{
URLreq = Uri1 + keyList[ab];
reqs.Add(URLreq);
}
foreach (string ra in reqs)
{
Uri uri = new Uri(ra);
// Create the web request
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(ra + " : " + reader.ReadToEnd());
}
}
Console.ReadLine();
}
Could you suggest how can I execute 100 requests using this loop, then pause for 2 seconds, then continue from loop 101 to 200, then pause, 201 to 300 etc.
Add an Counter into your method, something like this:
static void apiReq()
{
string filePath = "Path To File\\a.txt";
var fileLines = System.IO.File.ReadAllLines(filePath);
int requestCounter = 0; // Adding a counter
foreach(string s in fileLines)
{
keyList.Add(s);
}
for (int ab = 0; ab < keyList.Count; ab++)
{
URLreq = Uri1 + keyList[ab];
reqs.Add(URLreq);
}
foreach (string ra in reqs)
{
if (requestCounter % 100 == 0) // Every 100th step
{
Thread.Sleep(2000); // Wait for 2 seconds
}
Uri uri = new Uri(ra);
// Create the web request
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// ..
}
requestCounter++; // Count upwards
}
// ..
}
Thank you @Smartis !
I managed to do it with:
foreach (string ra in reqs)
{
for (int o = 0; o < reqs.Count; o++)
{
requestCounter = reqs.IndexOf(ra);
}
Uri uri = new Uri(ra);
// Create the web request
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(ra + " : " + reader.ReadToEnd());
}
if (requestCounter % 100 == 0) // Every 100th step
{
System.Threading.Thread.Sleep(2000); // Wait for 2 seconds
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.