多个HttpWebRequest同时使用POST

时间:2014-03-01 16:25:07

标签: c# parallel-processing httpwebrequest

我正在尝试将POST请求发送到Web服务器,它们都必须同时完成。
我已经制作了下面的代码,但它每秒发送大约4个请求。例如,如果我想发送20个POST请求,则大约需要6秒钟,并且它们不会按照我的要求同时发送。
我试图将ServicePointManager.DefaultConnectionLimit和ServicePointManager.MaxServicePoints设置得更高,但它仍然是相同的。

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);
}

1 个答案:

答案 0 :(得分:0)

您可以使用HttpClientPostAsync

您可以使用StringContent类传递第二个参数HttpContent,例如

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

请点击此处https://stackoverflow.com/a/13155225/1202600,了解同时关闭所有请求的示例,但GetAsync