C# 理解WebRequest

C# 理解WebRequest,c#,webrequest,streamreader,C#,Webrequest,Streamreader,我找到了这段代码,它允许您登录到网站并从登录页面获得响应。但是,我很难理解代码的所有部分。到目前为止,我已经尽了最大的努力来填写我所理解的内容。希望你们能帮我填空。谢谢 string nick = "mrbean"; string password = "12345"; //this is the query data that is getting posted by the website. //the query parameters 'nick' and 'password' mus

我找到了这段代码,它允许您登录到网站并从登录页面获得响应。但是,我很难理解代码的所有部分。到目前为止,我已经尽了最大的努力来填写我所理解的内容。希望你们能帮我填空。谢谢

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();

流是一个字节序列

为了在流中使用文本,需要将其转换为字节序列

这可以通过编码类手动完成,也可以通过
StreamReader
StreamWriter
自动完成。(将字符串读写到流)


如报告所述

您必须调用Stream.Close方法来关闭流并释放连接以供重用。关闭流失败会导致应用程序连接不足



方法和内容-*属性反映了基础属性。

您正在查找文档。您好,SLaks,您知道为什么postData必须位于字节数组中吗?@Nai:Streams包含字节,而不是字符串。不能通过网络直接发送字符串;您需要将其编码为字节数组。您也可以使用StreamWriter来代替。好的,谢谢!喂,你不认为你也可以看看这个问题的后续问题吗?