Reputation: 31
I want to send multiply post requests to a website. I've search over Google and got to this code:
class Program
{
public static HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create("http://example.com/login.php");
public static ASCIIEncoding encoding = new ASCIIEncoding();
public static string postData = "";
public static bool first = true;
static void Main(string[] args)
{
string uname = "", pass = "", Final = "";
while (1>0)
{
Console.WriteLine("Enter uname ,then password");
uname = Console.ReadLine();
pass = Console.ReadLine();
if (uname == "0")
break;
Final = letstry(uname, pass);
Console.WriteLine(Final);
Console.WriteLine("Finish That");
}
}
public static string letstry(string uname, string pass)
{
postData = "uname=" + uname;
postData += ("&pass=" + pass);
byte[] data = encoding.GetBytes(postData);
if (first)
{
HttpWReq.Method = "POST";
HttpWReq.ContentType = "application/x-www-form-urlencoded";
HttpWReq.ContentLength = data.Length;
first = !first;
}
Stream newStream = HttpWReq.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
WebResponse resp = HttpWReq.GetResponse();
StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
}
I'm getting an error that the connection was closed (newstream). Why can't I use the same connection to send more than one request?
The only idea that I can think about it's to send a stream var to letstry
, instead of creating newstream
.
I'm no expert, so I'm sorry for any unnecessary mistakes.
tyvm for your help:)
Upvotes: 3
Views: 1670
Reputation: 244968
WebRequest
is designed to do what it says: make one request. If you want to make multiple requests, just create new WebRequest
each time.
If the KeepAlive
property is true
, the requests try to use the same connection, if possible. See Understanding System.Net Connection Management and ServicepointManager for more information.
Upvotes: 3