I want to be able to send multiple GetRequest to a URL at the same time, and have it loop automatically. Can anyone give me the C# con开发者_JAVA百科sole coding?
This is the code:
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();
}
}
}
JK presents a synchronous version. The second URL won't be retrieved until a response is received from the first URL request.
Here's an asynchronous version:
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.
}
See DownloadDataAsync documentation
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;
}
精彩评论