以下代码已由 Fiddler 生成,并在 button_Click 事件中调用。
//Create request to URL.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://forums.codeguru.com/login.php?do=login");
//Set request headers.
request.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Headers.Set(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.5");
request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
request.Referer = "http://forums.codeguru.com/";
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
//Set request method
request.Method = "POST";
// Disable 'Expect: 100-continue' behavior. More info: http://haacked.com/archive/2004/05/15/http-web-request-expect-100-continue.aspx
request.ServicePoint.Expect100Continue = false;
//Set request body.
**// Fail**
string body = @"vb_login_username=**userid**&vb_login_password=&vb_login_password_hint=Password&s=&securitytoken=guest&do=login&vb_login_md5password=a35cef11bdd55e36423f8d3b1ed69dea&vb_login_md5password_utf=a35cef11bdd55e36423f8d3b1ed69dea";
byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
//Get response to request.
response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
var reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
string srcString = reader.ReadToEnd();
}
catch (WebException e)
{
//ProtocolError indicates a valid HTTP response, but with a non-200 status code (e.g. 304 Not Modified, 404 Not Found)
if (e.Status == WebExceptionStatus.ProtocolError) response = (HttpWebResponse)e.Response;
else return false;
}
catch (Exception)
{
if (response != null) response.Close();
return false;
}
return true;
}
button_Click 事件中的代码
HttpWebResponse response;
if (Request_forums_codeguru_com(out response))
{
//Success, possibly use response.
HttpStatusCode status = response.StatusCode;
// Status is alway OK
response.Close();
MessageBox.Show("Succesful login");
}
else
{
//Failure, cannot use response.
MessageBox.Show("Unsuccesful login");
}
但即使我输入了错误的密码,我也会得到 HttpStatus 为 OK。如何检查登录失败。
在最后阶段,我将从 Python 服务器接收数据,所以以上只是一个测试。
编辑 :
当用户输入错误的用户名/密码组合时,他/她会看到以下内容:-