Open url multiple times at the same times, like fiddler on c#

Ineed to pragmatically open one link multiple times at the same time, but the link must set cookies on the web, i finish this part but i cant repeat open url like fiddler, can you help me?

string url = "https://www.google.com.mx";
Uri target = new Uri(url);
CookieContainer gaCookies = new CookieContainer();
gaCookies.Add(new Cookie("dosid", textBox1.Text) { Domain = target.Host });
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
myReq.CookieContainer = gaCookies;
HttpWebResponse response = (HttpWebResponse)myReq.GetResponse();

Upvotes: 1

Views: 485

Answers (1)

CarCar
CarCar

Reputation: 680

Here is a simple way to do it using await/async. You really do not want to do too many at the same time. It would be best to implement a way to using maybe semaphores or something to only allow so many at a time to process. But this meets your requirements:

private async void button1_Click(object sender, EventArgs e)
{

    List<string> urls = new List<string>
    {
        "https://www.google.com.mx",
        "https://www.google.com.mx",
        "https://www.google.com.mx",
        "https://www.google.com.mx",
    };


    var tasks = new List<Task>();
    var results = new List<string>();

    foreach (string url in urls)
    {
        var webReq = (HttpWebRequest)WebRequest.Create(url);
        CookieContainer gaCookies = new CookieContainer();
        gaCookies.Add(new Cookie("dosid", textBox1.Text) { Domain = /*target.Host*/ "google.com" });
        webReq.CookieContainer = gaCookies;

        tasks.Add(GetURLContentsAsync(webReq));
    }

    await Task.WhenAll(tasks); //wait for all the urls to finish loading

    foreach (Task<string> task in tasks) //get the results of all the web requests
    {
        results.Add(await task);
    }

}

private async Task<string> GetURLContentsAsync(HttpWebRequest webReq)
{
    var content = new MemoryStream();

    using (WebResponse response = await webReq.GetResponseAsync())
    {
        using (Stream responseStream = response.GetResponseStream())
        {
            await responseStream.CopyToAsync(content);
        }
    }
    var buffer = content.ToArray();
    return Encoding.UTF8.GetString(buffer, 0, buffer.Length);
}

Upvotes: 1

Related Questions