如何在C#控制台应用程序中向URL发送多个get请求?

时间:2011-07-28 10:26:50

标签: c#

我希望能够同时向URL发送多个GetRequest,并让它自动循环。谁能给我C#控制台编码?

这是代码:

using System;
using System.Net;
using System.IO;

namespace MakeAGETRequest_charp
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
    static void Main(string[] args)
    {
        string sURL;
        sURL = "EXAMPLE.COM";

        int things = 5;
        while (things > 0)
        {
            WebRequest wrGETURL;
            wrGETURL = WebRequest.Create(sURL);

            Stream objStream;
            objStream = wrGETURL.GetResponse().GetResponseStream();

            StreamReader objReader = new StreamReader(objStream);

            string sLine = "1";
            int i = 0;

                i++;
                sLine = objReader.ReadLine();
                if (things > 0)
                    Console.WriteLine("{0}:{1}", i, sLine);
            }
            Console.ReadLine();
        }
    }
}

2 个答案:

答案 0 :(得分:2)

JK呈现同步版本。在收到第一个URL请求的响应之前,将不会检索第二个URL。

这是一个异步版本:

List<Uri> uris = new List<Uri>();
uris.Add(new Uri("http://example.com"));
uris.Add(new Uri("http://example2.com"));

foreach(Uri u in uris)
{
    var client = new WebClient();

    client.DownloadDataCompleted += OnDownloadCompleted;
    client.DownloadDataAsync(u); // this makes a GET request
}

...

void OnDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    // do stuff here.  check e for completion, exceptions, etc.
}

请参阅DownloadDataAsync documentation

答案 1 :(得分:0)

List<Uri> uris = new List<Uri>();
uris.Add(new Uri("http://example.com"));
uris.Add(new Uri("http://example2.com"));

foreach(Uri u in uris)
{
    WebRequest request = HttpWebRequest.Create(u);
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
}
相关问题