Good day. The challenge was to send a POST request to the site using C # and receive a response in the form of html. I use the following code for this:

private static string POST(string Url, string Data) { System.Net.WebRequest req = System.Net.WebRequest.Create(Url); req.Method = "POST"; req.Timeout = 100000; req.ContentType = "application/x-www-form-urlencoded"; byte[] sentData = Encoding.GetEncoding(1251).GetBytes(Data); req.ContentLength = sentData.Length; System.IO.Stream sendStream = req.GetRequestStream(); sendStream.Write(sentData, 0, sentData.Length); sendStream.Close(); System.Net.WebResponse res = req.GetResponse(); System.IO.Stream ReceiveStream = res.GetResponseStream(); System.IO.StreamReader sr = new System.IO.StreamReader(ReceiveStream, Encoding.UTF8); //Кодировка указывается в зависимости от кодировки ответа сервера Char[] read = new Char[256]; int count = sr.Read(read, 0, 256); string Out = String.Empty; while (count > 0) { String str = new String(read, 0, count); Out += str; count = sr.Read(read, 0, 256); } return Out; } string Answer = POST("http://testsite.ru/", "login=Andrey&password=pass word"); 

The problem is that one of the parameters of the POST request may contain a space. Please tell me how can I pass this parameter?

  • I tried various settings and found the following behavior: when specifying the wrong bundle of logs / password, I get in response to the html-code of the page with information about incorrect login or password input. At the same time, when the login / password is correct, the authorization does not occur and I get the html code of the authorization page as an answer. - gde_ob

2 answers 2

Try using HttpUtility.UrlEncode

 "login=Andrey&password=" + HttpUtility.UrlEncode("pass word") 
  • The function HttpUtility.UrlEncode ("pass word") converts the string "pass word" into the string "pass + word". This is not for me, because when converted to bytes, the function Encoding.GetEncoding (1251) .GetBytes (Data) "+" is perceived as "+", and not as a space and authorization fails. - gde_ob

Use: