Понимание веб-запроса

Я нашел этот фрагмент кода здесь, который позволяет вам войти на веб-сайт и получить ответ со страницы авторизации. Однако у меня возникли проблемы с пониманием всей части кода. Я старался изо всех сил, чтобы заполнить все, что я понимаю до сих пор. Надеюсь, вы, ребята, сможете заполнить пробелы для меня. Спасибо

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

person super9    schedule 29.12.2010    source источник
comment
Вы ищете документацию.   -  person SLaks    schedule 29.12.2010


Ответы (1)


Поток — это последовательность байтов.

Чтобы использовать текст с потоком, вам нужно преобразовать его в последовательность байтов.

Это можно сделать вручную с помощью классов Encoding или автоматически с помощью StreamReader и StreamWriter. (которые читают и записывают строки в потоки)


Как указано в документации для GetRequestStream,

Вы должны вызвать метод Stream.Close, чтобы закрыть поток и освободить соединение для повторного использования. Неспособность закрыть поток приводит к тому, что у вашего приложения заканчиваются соединения.


Свойства Method и Content-* отражают базовый протокол HTTP.

person SLaks    schedule 29.12.2010
comment
Привет, SLaks, ты знаешь, почему postData должен быть в массиве байтов? - person super9; 29.12.2010
comment
@Nai: потоки содержат байты, а не строки. Вы не можете напрямую отправить строку по сети; вам нужно закодировать его в массив байтов. - person SLaks; 29.12.2010
comment
Вместо этого вы также можете использовать StreamWriter. - person SLaks; 29.12.2010
comment
Хорошо, спасибо, чувак! Скажите, а не могли бы вы также взглянуть на дополнительный вопрос к этому? stackoverflow.com/questions/4555334/ - person super9; 29.12.2010