我找到了这段代码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();
答案 0 :(得分:2)
Stream是一个字节序列。
为了将文本与Stream一起使用,您需要将其转换为字节序列。
这可以使用编码类手动完成,也可以使用StreamReader
和StreamWriter
自动完成。 (读取和写入流的字符串)
如documentation for GetRequestStream
中所述,
您必须调用Stream.Close方法关闭流并释放连接以便重用。无法关闭流会导致应用程序用完连接。
Method和Content- *属性反映了基础HTTP protocol。