2010-12-29 9 views
0

웹 사이트에 로그인하고 로그인 한 페이지에서 응답을받을 수있는이 코드 스 니펫 here을 발견했습니다. 그러나 코드의 모든 부분을 이해하는 데 문제가 있습니다. 나는 지금까지 내가 이해하는 것을 채우기 위해 최선을 다했다. 너희들이 나를 위해 공란을 채울 수 있기를 소망한다. 감사합니다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

스트림은 일련의 바이트입니다.

스트림에서 텍스트를 사용하려면 바이트 시퀀스로 변환해야합니다.

이 작업은 Encoding 클래스를 사용하여 수동으로 수행하거나 StreamReaderStreamWriter을 사용하여 자동으로 수행 할 수 있습니다. (스트림에 문자열을 읽기 및 쓰기 있음) documentation for GetRequestStream에 명시된 바와 같이


,

당신은 스트림을 닫고 재사용에 대한 연결을 해제하기 위해 Stream.Close 메서드를 호출해야합니다. 스트림을 닫지 않으면 응용 프로그램의 연결이 끊어집니다.


방법 및 콘텐츠 - * 속성은 기본 HTTP protocol을 반영한다.

+0

안녕하세요 SLaks, 이유는 postData 바이트 배열에 있어야 알아? – super9

+0

@Nai : 스트림은 문자열이 아니라 바이트를 보유합니다. 네트워크를 통해 문자열을 직접 보낼 수는 없습니다. 그것을 바이트 배열로 인코딩해야합니다. – SLaks

+0

대신 StreamWriter를 사용할 수도 있습니다. – SLaks