2014-03-01 21 views
1

我想發送POST請求到Web服務器,它們都必須在同一時間完成。
我已經制作了下面的代碼,但它發送的請求大約每秒4個。例如,如果我想發送20個POST請求,則需要大約6秒鐘,並且不會按照我的需要同時發送。
我試圖設置ServicePointManager.DefaultConnectionLimit和ServicePointManager.MaxServicePoints更高,但它仍然是相同的。同時POST多個HttpWebRequest

class BrowserAsync 
{ 
    private HttpWebRequest WebReq; 

    public void makePOST(string url, string POST) 
    { 
     byte[] buffer = Encoding.ASCII.GetBytes(POST); 
     WebReq = (HttpWebRequest)WebRequest.Create(url); 

     WebReq.Headers.Clear(); 
     // CUSTOM HEADERS HERE -- not shown in this example 

     WebReq.KeepAlive = false; 
     WebReq.Proxy = null; 

     WebReq.Method = "POST"; 
     WebReq.ContentType = "application/x-www-form-urlencoded"; 
     WebReq.ContentLength = buffer.Length; 

     Stream PostData = WebReq.GetRequestStream(); 
     PostData.Write(buffer, 0, buffer.Length); 
     PostData.Close(); 

     WebReq.BeginGetResponse(new AsyncCallback(FinishWebRequest), null); 
    } 

    private void FinishWebRequest(IAsyncResult result) 
    { 
     // data returned is not important, just end it 
     WebReq.EndGetResponse(result); 
    } 
} 



每個實例正從它自己的線程中調用:

public static void waitAndExecute(object threadInfo) 
{ 
    // this is the thread on it's own 
    ThreadInformation info; 
    info = (ThreadInformation)threadInfo; 

    // WAIT 
    // Display("Sleeping until " + DateTime.Now.AddMilliseconds((info.exTime - DateTime.Now).TotalMilliseconds - info.ping) 
    // the same sleeping time is displayed for all threads 
    System.Threading.Thread.Sleep((int)(info.exTime - DateTime.Now).TotalMilliseconds - info.ping); 

    BrowserAsync brw = new BrowserAsync(); 
    brw.makePOST("url", info.postParameters); 
} 
+0

什麼是你的問題踢所有的請求關閉的例子嗎?你有錯誤嗎?你期望的結果是什麼,你得到了什麼結果? –

+0

我想同時發送20個POST。我沒有收到任何錯誤。結果是,前4個帖子在第1秒發送,其他4個在第2秒發送,等等...... – Doctorslo

+0

你用什麼代碼調用waitAndExecute方法20次?此外什麼設置信息的exTime和ping屬性? – thudbutt

回答

0

你可以使用HttpClientPostAsync

您可以使用StringContent類例如傳遞第二個參數HttpContent。

var client = new HttpClient(); 
client.PostAsync(url, new StringContent(POST)); 

看到這裏https://stackoverflow.com/a/13155225/1202600在同一時間,但有GetAsync