我有一个方法,我用来登录网站。每次,此方法都会创建一个新的Webrequest和Webresponse,它在前两次工作正常。但是,我第三次调用它时,它会挂起(在using (Stream stream = request.GetRequestStream())
行)。我不知道为什么。我正在处理一切。这是我的方法:
public static void Login()
{
//Create HTTP request
HttpWebRequest request =
WebRequest.CreateHttp("https://www.mcgamerzone.com/login?username=username&url=/settings/security");
//Set request headers
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.KeepAlive = true;
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0";
request.Method = "POST";
request.Headers = new WebHeaderCollection {
{"Accept-Language", "en-US,en;q=0.5"}
};
//Post data
Dictionary<string, string> postDict = new Dictionary<string, string> {
{"login", "Login"},
{"password", "password"},
{"username", "username"}
};
//Post data as byte array
byte[] postData = new FormUrlEncodedContent(postDict).ReadAsByteArrayAsync().Result;
request.ContentLength = postData.Length;
request.ContentType = "application/x-www-form-urlencoded";
//Write post data to request stream
using (Stream stream = request.GetRequestStream())
stream.Write(postData, 0, postData.Length);
}
然后在控制台应用程序中使用它:
static void Main(string[] args)
{
Login();
Console.WriteLine("Logged in");
Login();
Console.WriteLine("Logged in");
Login();
Console.WriteLine("Logged in");
}
&#34;登录&#34;在控制台中出现2次。第三个出现大约需要3分钟 我无法弄清楚它悬挂的原因。当然,这不是因为我没有正确处理对象,因为我每次都在创建一个新对象。 Wireshark表明它没有向服务器发送信息,服务器也没有发送信息。