Hello, let's get straight to the point. I try to master httpwebrequest, I want to parse something which values ​​from the site to which you first need to log in via https, and I can’t understand what I’m missing, because every time I get an answer that the login and password are not correct. Please tell me how to do it.

var request = (HttpWebRequest)HttpWebRequest.Create("https://login.bookatable.com/Common/Logon"); request.ContentType = "application/json"; request.Method = "POST"; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (var sw = new StreamWriter(request.GetRequestStream())) { string json = "userEmail=my@email.com&password=MyP@$$worD&selectedCulture=en-GB"; sw.Write(json); sw.Flush(); sw.Close(); } var response = (HttpWebResponse)request.GetResponse(); using (var sr = new StreamReader(response.GetResponseStream())) { var result = sr.ReadToEnd(); textBox1.Text = result; } 

when I send a request to / Common / Logon I get an error of the server E-20180130-218A4EF5F8 when I send a request to / login it says that the password or email is not correct ! [enter image description here

enter image description here

  • Look carefully at what the server takes if you go through the site. You are sending to the "/ Common / Logon" data not in JSON , but in the usual form, that is, Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Content-Type: application/x-www-form-urlencoded; charset=UTF-8 . I also note that your data that you are trying to send right now is not JSON , but a regular data set. JSON should look something like this {"param" : "value", "param2" : true} . - EvgeniyZ
  • thanks, everything worked out - Just_Deniss
  • Let's close the question then. Compiled the answer, put a "daw" on the side, if he helped you. - EvgeniyZ

1 answer 1

Let's see what the server should get:

  • To do this, open the program to catch all requests (in your case this is Fiddler).
  • Configure it to track requests.
  • We go to the desired site and make the standard authorization using the form.
  • Our program should receive the request itself with all its "internals".

Well, we look at what we send: We send POST a Cookie request, the request body of the application/x-www-form-urlencoded format and in the UTF-8 encoding, as well as any parameters like Referer and others. Often, for a successful response it is enough for us to compose competently, the "body" of the request, in some cases, more Cookie are required, and in some cases all the parameters must be identical. In your case, I think you just need to competently send the body to the desired address.

I personally love using HttpClient . I will show on his example what we need:

 public async Task<string> SendRequest(CancellationToken ct) { string data; var baseAddress = new Uri("https://..."); //Базовый адрес var url = "/login"; //Нужная нам страница, на которую пойдет запрос var cookieContainer = new CookieContainer(); //Показываю как отправлять Cookie (для примера, если необходимо). Можно убрать. using (var handler = new HttpClientHandler { CookieContainer = cookieContainer }) using (var client = new HttpClient(handler) { BaseAddress = baseAddress }) { client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36 OPR/49.0.2725.64"); //Добавляем нужные нам параметры в запрос (на примере UserAgent'a) cookieContainer.Add(baseAddress, new Cookie("lang", "en")); //Добавляем необходимые Cookie var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("login", "xxxxx"), new KeyValuePair<string, string>("pass", "yyyyy") }); //Наше тело, которое при помощи FormUrlEncodedContent закодируется в нужное нам "тело". var result = await client.PostAsync(url, content, ct); //Отправляем на нужную страницу POST запрос с нашем телом, также тут используется CancellationToken для грамотной отмены async методов. var bytes = await result.Content.ReadAsByteArrayAsync(); Encoding encoding = Encoding.GetEncoding("utf-8"); data = encoding.GetString(bytes, 0, bytes.Length); //Все эти три строки добавлены тут для того, что бы получать данные в нужной нам кодировке (некоторые сервера к примеру выдают в неверной кодировке и может выдать ошибку). Вообще можно все 3 строки заменить на одну: //data = await result.Content.ReadAsStringAsync(); Тогда кодировка будет той, что выдает сервер. result.EnsureSuccessStatusCode(); } return data; } 

It seems everywhere where it is necessary to leave comments, there will be no difficulties.

In general, to summarize: Judging by what you provided and what I saw when viewing the login page, the output is simple, your request sends the wrong format, namely application/json , when the server itself waits from you application/x-www-form-urlencoded . Also, if we say the server would accept the JSON body, you write the JSON yourself incorrectly, the format should be {"param" : "value", "param2" : true} or something similar.