开发者

Understanding WebRequest

I found this snippet of code here that allows you to log into a website and get the response from the logged in page. However, I'm having trouble understanding all the part of the code. I've tried my best to fill in whatever I understand so far. Hope you guys can fill in the blanks for me. Thanks

string nick = "mrbean";
string password = "12345";

//this is the开发者_C百科 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();


A Stream is a sequence of bytes.

In order to use text with a Stream, you need to convert it into a sequence of bytes.

This can be done manually with the Encoding classes or automatically with StreamReader and StreamWriter. (which read and write strings to streams)


As stated in the documentation for GetRequestStream,

You must call the Stream.Close method to close the stream and release the connection for reuse. Failure to close the stream causes your application to run out of connections.


The Method and Content-* properties reflect the underlying HTTP protocol.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜