V
V
Vyacheslav Shabunin2020-10-06 16:16:05
C++ / C#
Vyacheslav Shabunin, 2020-10-06 16:16:05

How to pass POST headers through HttpRequest?

Hello. Help with an example please. For example, I took the Yandex job site, for example, I need to click on the button to add a certain vacancy to favorites and track feedback through Response.
Having parsed the headers, I have the following:
5f7c6a3d87aec599033257.png
How to determine a specific request for clicking a button, I have not yet understood, well, let it be 1: 1276757? %3App%3A3629563401
Next we have the headers that I need to pass back, again I think I need to look at the Request Headers!??
Okay, I enter them like this:

string url = "https://rabota.yandex.ru/chelyabinsk/vakansii/"
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST"
req.Connection = "keep-alive"

etc. But after listing all the headers, it's not clear to me what to do next.
Besides the fact that you will need to call the object for HttpWebRespnce.
Please help with an example, for a general understanding, Google does not describe how to transfer headers back, what specific information, for example, I need to encrypt into bytes, and what exactly to transfer. I can understand with an example.
5f7c6d3f11dd0455719866.png
5f7c6d6e3c830461339624.png

It is not yet clear which specific headers I should send along with cookies, and which ones are optional. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
cicatrix, 2020-10-07
@fleshherbal

In a nutshell, after creating a request, you need to open a RequestStream, write all POST data to it and send it to the server.
Here I pulled out a POST request from the finished project:

// в data передаются параметры POST (ключ - значение)
// если надо загрузить файл - передаётся в file
internal static string Post(string url, Dictionary<string, string> data, FileUploadData file = null)
        {
            string ServerResponse = null;
            HttpWebRequest wrq = (HttpWebRequest)HttpWebRequest.Create(url);
            wrq.Method = WebRequestMethods.Http.Post;
            wrq.UserAgent = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + 
                            System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            wrq.Timeout = 600000;
            try
            {
                // Это на случай использования прокси, можно выкинуть
                if (Config.UseProxy)
                {
                    WebProxy proxy = new WebProxy(Config.ProxyAddress, Config.ProxyPort);
                    if (Config.ProxyLogin != string.Empty || Config.ProxyPass != string.Empty)
                    {
                        proxy.Credentials = new NetworkCredential(Config.ProxyLogin, Config.ProxyPass);
                        proxy.UseDefaultCredentials = false;
                    }
                    else
                    {
                        proxy.UseDefaultCredentials = true;
                    }
                }

                if (null == file) // проверяем, надо ли загружать файл на сервер
                {
                    wrq.ContentType = "application/x-www-form-urlencoded";
                    Stream requestStream = wrq.GetRequestStream();
                    List<string> keydata = new List<string>();
                    foreach (string key in data.Keys)
                    {
                        keydata.Add($"{HttpUtility.UrlEncode(key)}={HttpUtility.UrlEncode(data[key])}");
                    }
                    WriteToStream(requestStream, string.Join("&", keydata));
                    requestStream.Flush();
                }
                else
                {
                    // Формируем multipart/form-data (отправка данных с формы)
                    string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
                    wrq.ContentType = "multipart/form-data; boundary =" + boundary;
                    Stream requestStream = wrq.GetRequestStream();
                    WriteMultipartForm(requestStream, boundary, data, file);
                }
                // Посылаем данные на сервер и ждём ответа
                wrq.BeginGetResponse(a =>
                {
                    try
                    {
                        WebResponse resp = wrq.EndGetResponse(a);
                        Stream respStr = resp.GetResponseStream();
                        using (StreamReader sr = new StreamReader(respStr))
                        {
                            ServerResponse = sr.ReadToEnd();
                        } // using sr
                } // try
                catch (Exception ex)
                    {
                        Logger.LogError("Transport.Post", Globalizer.ID_Transport_Request_executing_error, ex);
                    } // catch
            }, null);
            }  // try
            catch(Exception ex)
            {
                Logger.LogError("Transport.Post", Globalizer.ID_Transport_Could_not_connect_to_server, ex);
                return null;
            }
            return ServerResponse;
        } // Post

private static void WriteMultipartForm(Stream s, string boundary, Dictionary<string, string> data, FileUploadData file)
        {
            /// The first boundary
            byte[] boundarybytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
            /// the last boundary.
            byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
            /// the form data, properly formatted
            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            /// the form-data file upload, properly formatted
            string fileheaderTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\";\r\nContent-Type: {2}\r\n\r\n";

            /// Added to track if we need a CRLF or not.
            bool bNeedsCRLF = false;

            if (data != null)
            {
                foreach (string key in data.Keys)
                {
                    /// if we need to drop a CRLF, do that.
                    if (bNeedsCRLF)
                        WriteToStream(s, "\r\n");

                    /// Write the boundary.
                    WriteToStream(s, boundarybytes);

                    /// Write the key.
                    WriteToStream(s, string.Format(formdataTemplate, key, data[key]));
                    bNeedsCRLF = true;
                }
            }

            /// If we don't have keys, we don't need a crlf.
            if (bNeedsCRLF)
                WriteToStream(s, "\r\n");

            WriteToStream(s, boundarybytes);
            WriteToStream(s, string.Format(fileheaderTemplate, file.FieldName, file.Filename, file.ContentType));
            /// Write the file data to the stream.
            WriteToStream(s, file.FileData);
            WriteToStream(s, trailer);
        }

private static void WriteToStream(Stream s, string txt)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(txt);
            s.Write(bytes, 0, bytes.Length);
        } // WriteToStream

V
Vasily Bannikov, 2020-10-06
@vabka

I did not understand the question, it did not work with HttpWebRequest.
As an alternative and more modern solution, I can offer HttpClient and HttpRequestMessage, the message has just a property for specifying the headers of all.
If HttpClient scares you, then pay attention to flurl.
According to optional headings - in theory, this is all, then you can then add everything in order, I don’t know what Yandex checks work there

V
Vyacheslav Shabunin, 2020-10-06
@fleshherbal

And the essence of the question is that I do not know what to do next after specifying all the headers, there is no information as such. Rather, it is, but it is very brief and does not explain much the essence of my question.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question