Reputation: 13
I wanted do POST
a WebRequest
for a Browser game in a loop because the POST
content contains a number. Now I have a frozen program.
Here is my Code:
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);
}
The Ouput is:
FriendlyNr: 1
And the Browsergame got only the one Post Content.
So the first run is working but the second rund did not work. The Programm freezes at
Stream stream = req.GetRequestStream();
I want to loop 10 times. How to achieve that?
Upvotes: 1
Views: 2524
Reputation: 1484
You are using the same Stream
object - you need to use a new HttpRequest
each time. Take a look here to see a potential solution. Make sure you are also closing the Stream
object as well.
Additionally, putting the code in a using statement such as using (var requestStream = request.GetRequestStream())
will help make sure that the object is disposed of and collected appropriately.
Upvotes: 1