我找到了这段代码here,它允许您登录网站并从登录页面获取响应。然而,我在理解代码的所有部分时遇到了问题。到目前为止,我已经尽了最大努力填写我所理解的内容。希望你们能帮我填空。谢谢
string nick = "mrbean";
string password = "12345";
//this is the query data that is getting posted by the website.
//the query parameters 'nick' and 'password' must match the
//name of the form you're trying to log into. you can find the input names
//by using firebug and inspecting the text field
string postData = "nick=" + nick + "&password=" + password;
// this puts the postData in a byte Array with a specific encoding
//Why must the data be in a byte array?
byte[] data = Encoding.ASCII.GetBytes(postData);
// this basically creates the login page of the site you want to log into
WebRequest request = WebRequest.Create("http://www.mrbeanandme.com/login/");
// im guessing these parameters need to be set but i dont why?
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
// this opens a stream for writing the post variables.
// im not sure what a stream class does. need to do some reading into this.
Stream stream = request.GetRequestStream();
// you write the postData to the website and then close the connection?
stream.Write(data, 0, data.Length);
stream.Close();
// this receives the response after the log in
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
// i guess you need a stream reader to read a stream?
StreamReader sr = new StreamReader(stream);
// this outputs the code to console and terminates the program
Console.WriteLine(sr.ReadToEnd());
Console.ReadLine();发布于 2010-12-29 11:28:02
流是一个字节序列。
为了在Stream中使用文本,您需要将其转换为字节序列。
这可以使用Encoding类手动完成,也可以使用StreamReader和StreamWriter自动完成。(将字符串读写到流中)
正如documentation for GetRequestStream中所述,
您必须调用Stream.Close方法来关闭流并释放连接以供重用。如果不能关闭流,则会导致应用程序耗尽连接。
方法和Content-*属性反映了底层的HTTP protocol。
https://stackoverflow.com/questions/4551247
复制相似问题