2010-12-29 14 views
0

コードhereのこのスニペットを見ると、Webサイトにログインしてログインしたページから応答を得ることができます。しかし、私はコードのすべての部分を理解することに問題があります。私はこれまでに理解していることを記入するために最善を尽くしました。あなたは私のために空白を埋めることができることを願っています。ありがとうWebRequestの理解

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

あなたはドキュメントを探しています。 – SLaks

答えて

2

ストリームは一連のバイトです。

ストリームでテキストを使用するには、バイトシーケンスに変換する必要があります。

これは、エンコードクラスを使用して手動で行うことも、StreamReaderStreamWriterで自動的に行うこともできます。 (ストリームに文字列を読み書きする)documentation for GetRequestStreamで述べたように


あなたはストリームを閉じて、再利用のための接続を解放するためにStream.Closeメソッドを呼び出す必要があります。ストリームを閉じないと、アプリケーションの接続が不足します。


方法とのContent *プロパティは、基礎となるHTTP protocolを反映しています。

+0

こんにちはSLaks、あなたはバイト配列でpostDataをする必要があります知っていますか? – super9

+0

@Nai:文字列ではなくストリームのホールドバイト。ネットワーク上で文字列を直接送信することはできません。それをバイト配列にエンコードする必要があります。 – SLaks

+0

代わりにStreamWriterを使用することもできます。 – SLaks