我想将多个帖子请求发送到网站。 我搜索了Google并获得了此代码:
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();
}
}
我收到连接已关闭的错误(newstream)。 为什么我不能使用相同的连接发送多个请求?
我能想到的唯一想法是将流变量发送到letstry
,而不是创建newstream
。
我不是专家,所以我很抱歉任何不必要的错误。
tyvm求助:)
答案 0 :(得分:3)
WebRequest
的目的是做它所说的:提出一个请求。如果您想要发出多个请求,请每次都创建新的WebRequest
。
如果KeepAlive
属性为true
,则请求尝试使用相同的连接(如果可能)。有关详细信息,请参阅Understanding System.Net Connection Management and ServicepointManager。