2011-07-28 20 views
1

我希望能夠同時向一個URL發送多個GetRequest,並讓它自動循環。任何人都可以給我C#控制檯編碼嗎?如何向C#控制檯應用程序中的URL發送多個獲取請求?

這是代碼:

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(); 
     } 
    } 
} 
+0

這是什麼呢? – AndyBursh

+1

如果您發佈了迄今已編碼的內容,我們可以幫助您解決問題。否則,我建議你執行一個關於如何完成GetRequest的快速谷歌,然後如果你不能修改代碼以適應你的需求,那麼回到這裏。沒有你已經嘗試過的一些樣本,你不會找到太多的人幫助... –

+0

這是我的,但我希望它在同一時間發送多個請求。我能得到的信息越多,越好。 編輯:我在這裏是新來的,即時通訊粘貼代碼時遇到麻煩,它說它太大了。 – ThatsSo

回答

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; 
} 
+0

這不是用戶想要的,他希望同時不是一個接一個地使用線程或taks或asynchorous將會產生效果 – K3rnel31

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

+0

您是否需要爲每個請求創建一個WebClient,或者是否可以創建它並將回調處理程序設置爲外部循環重新使用它? – ZombieSheep

+0

我會創建一個每個請求。我不確定,但我認爲這可能是有意的。例如,WebClient的CancelAsync()方法不會指定取消哪個掛起的操作(如果允許多個)。 – jglouie

+0

你說得對。當我嘗試引發兩個併發下載時 - 「WebClient不支持併發I/O操作」時,我剛剛玩過一個WebClient並得到以下NotSupportedException。你每天學習新的東西。 :) – ZombieSheep

相關問題