c# HttpWebRequest "POST" 带循环

c# HttpWebRequest "POST" with Loop

我想在循环中为浏览器游戏做 POST WebRequest,因为 POST 内容包含一个数字。现在我有一个冻结的程序。

这是我的代码:

String loginData = "login";

// Set Cookie 
CookieContainer cookieContainer = new CookieContainer();

// Login

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("URL");
req.CookieContainer = cookieContainer;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] loginDataBytes = encoding.GetBytes(loginData);
req.ContentLength = loginDataBytes.Length;
Stream stream = req.GetRequestStream();
stream.Write(loginDataBytes, 0, loginDataBytes.Length);
stream.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();

// Start the Loop

for (int i=1; i < 10; i++)
{

    String Friendly = "frday=" + i;

    req = (HttpWebRequest)HttpWebRequest.Create("URL");
    req.CookieContainer = cookieContainer;
    req.Method = "POST";
    req.ContentType = "application/x-www-form-urlencoded";
    byte[] Fr = encoding.GetBytes(Friendly);
    req.ContentLength = Fr.Length;

    Stream stream = req.GetRequestStream();
    stream.Write(Fr, 0, Fr.Length);
    stream.Close();

    Console.WriteLine("FriendlyNr: " + i);
}

输出是:

FriendlyNr: 1

而 Browsergame 只得到一个 Post 内容。

所以第一个 运行 有效,但第二个 运行d 无效。程序冻结在

Stream stream = req.GetRequestStream();

我要循环10次。如何实现?

您正在使用同一个 Stream 对象 - 您每次都需要使用一个新的 HttpRequest。查看 here 以了解可能的解决方案。确保您也关闭了 Stream 对象。

此外,将代码放在 using (var requestStream = request.GetRequestStream()) 等 using 语句中将有助于确保正确处理和收集对象。