我无法将其转换为 HTTPWebRequest。我使用 WebBrowser 让它完美地工作,但每当我尝试发出 HTTPWebRequest 时,它都会失败。我不确定我做错了什么。
工作代码:
private void Login()
{
WebBrowser b = new WebBrowser();
b.ScriptErrorsSuppressed = true;
username = textBox1.Text;
password = textBox2.Text;
string PostData = string.Format("username={0}&password={1}&rk24={2}", username, password, rk24);
ASCIIEncoding enc = new ASCIIEncoding();
b.Navigate(url, "", enc.GetBytes(PostData), "Content-Type: application/x-www-form-urlencoded\r\n");
b.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
}
private void b_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser b = sender as WebBrowser;
string response = b.DocumentText;
if (response.Contains("Sign out"))
{
this.Text = "LOGGED IN";
b.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
}
if (response.Contains("your info was incorrect"))
{
b.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
this.Text = "LOGIN ERROR";
MessageBox.Show("Invalid username or password!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
这是我对不起作用的 HTTPWebRequest 的尝试...
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
ASCIIEncoding enc = new ASCIIEncoding();
string postData = string.Format("username={0}&password={1}&rk24={2}", user, pass, rk24);
byte[] data = enc.GetBytes(postData);
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string responseFromServer = reader.ReadToEnd();
if(responseFromServer.Contains("Sign out"))
{
MessageBox.Show("Logged In!");
}
if (responseFromServer.Contains("your info was incorrect"))
{
MessageBox.Show("Invalid username or password");
}