Basser Basser - 25 days ago 13
C# Question

WebRequest cannot get the request stream

I am trying to make a HttpWebRequest which registers accounts for me.
I'm using a loop for it to register new accounts with only 1 thing changing, the username.
But for some reason it only works twice, the third time it will reach a certain line calling the function "webRequest.GetRequestStream();" and it will never finish that, it will not throw an error or anything.
This is my first HttpWebRequest, and it is very messy.
For people wondering, value is a string with the registration 'values' in there. The first 2 times do actually register the accounts, so it does work.

public static HttpWebRequest Get()
{
HttpWebRequest webRequest = WebRequest.Create("http://87.255.55.218/register") as HttpWebRequest;
webRequest.Method = "POST";
webRequest.Host = "87.255.55.218";
webRequest.UserAgent = "Hacker";
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
webRequest.Referer = "http://yougothacked.com";
webRequest.ContentType = "application/x-www-form-urlencoded";

webRequest.Headers.Add(HttpRequestHeader.KeepAlive, "115");
return webRequest;
}

public static void Register(string username)
{
string value = Value.Replace("replace", username);
WebRequest webRequest = Get();
webRequest.ContentLength = value.Length;
Thread.Sleep(50);
Stream reqStream = webRequest.GetRequestStream();

reqStream.Write(Encoding.ASCII.GetBytes(value), 0, value.Length);
Thread.Sleep(50);
reqStream.Flush();
reqStream.Close();
reqStream.Dispose();
}


What could be wrong?

Answer

I strongly suspect that the problem is in some code you haven't shown - namely that when you use the request, you're not disposing of the response properly. (Just like you should put the code using the request stream in a using block.)

If you don't dispose of the response, that response will hold onto a connection to the server until a finalizer releases it. Connections to individual servers are pooled.

In short: make sure you put the response in a using block like this:

using (WebResponse response = req.GetResponse())
{
    ...
}

and I suspect you'll find it works however many requests you make.

On the other hand, using WebClient as Darin suggested may well make your life simpler.

Comments