Missing message data using HttpWebRequest

I am having a problem sending data using HttpWebRequest .

There is a line (i.e. key1=value1&key2=value2&key3=value3 ) and I post it on the site (i.e. www. *. Com / edit), but I don’t know why this is sometimes wrong, but sometimes, the first key=value1 will be absent, only key2=value&key3=value3 , which can be found in HttpAnalyzer .

 public static string SubmitData(string Url, string FormData, CookieContainer _Cc, string ContentType) { Stream RequestStream = null, ResponseStream = null; StreamReader Sr = null; HttpWebRequest HRequest = (HttpWebRequest)WebRequest.Create(Url); try { HRequest.CookieContainer = _Cc; HRequest.Method = "POST"; HRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)"; HRequest.ContentType = ContentType; HRequest.ContentLength = FormData.Length; //byte[] BFromData = new ASCIIEncoding().GetBytes(FormData); byte[] BFromData = Encoding.ASCII.GetBytes(FormData); BFromData = Encoding.Convert(Encoding.ASCII, Encoding.UTF8, BFromData);//ascii β†’ utf8 RequestStream = HRequest.GetRequestStream(); RequestStream.Write(BFromData, 0, BFromData.Length); //RequestStream.Write(utf8Bytes,0,utf8Bytes.Length ); HttpWebResponse HResponse = (HttpWebResponse)HRequest.GetResponse(); ResponseStream = HResponse.GetResponseStream(); Sr = new StreamReader(ResponseStream, Encoding.UTF8); return Sr.ReadToEnd(); } catch { return ""; } finally { if (null != RequestStream) RequestStream.Close(); if (null != ResponseStream) ResponseStream.Close(); if (null != Sr) Sr.Close(); } } 
+4
source share
1 answer

Use Fiddler to see what the request looks like when you click on the form, then try using this approach and change what you need for your request.

 public static void PostDataAndDoSomething() { string URI = "http://www.something.com"; //make your request payload string requestBody = String.Format("{{'param1': {0}, 'param2': {1}}}",value1, value2); //json format HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URI); //make request // set request headers as you need request.ContentType = "application/json; charset=UTF-8"; request.Accept = "application/json, text/javascript; request.Method = "POST"; request.UserAgent = ""; request.Headers.Add("X-Requested-With", "XMLHttpRequest"); using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) { writer.Write(requestBody); //write your request payload } WebResponse response = request.GetResponse(); string jsonData = String.Empty; using (var reader = new StreamReader(response.GetResponseStream())) { jsonData = reader.ReadToEnd(); } response.Close(); //do something with your data, deserialize, Regex etc.... } 
+3
source

Source: https://habr.com/ru/post/1444053/


All Articles