Send an HTTP POST request using C #

I am trying to send data using WebRequest using POST. But my problem: no data is transferred to the server.

string user = textBox1.Text; string password = textBox2.Text; ASCIIEncoding encoding = new ASCIIEncoding(); string postData = "username" + user + "&password" + password; byte[] data = encoding.GetBytes(postData); WebRequest request = WebRequest.Create("http://localhost/s/test3.php"); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; Stream stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Close(); WebResponse response = request.GetResponse(); stream = response.GetResponseStream(); StreamReader sr99 = new StreamReader(stream); MessageBox.Show(sr99.ReadToEnd()); sr99.Close(); stream.Close(); 

here is the result

+6
source share
1 answer

This is because you need to set your published parameters with a = sign:

 byte[] data = Encoding.ASCII.GetBytes( $"username={user}&password={password}"); WebRequest request = WebRequest.Create("http://localhost/s/test3.php"); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } string responseContent = null; using (WebResponse response = request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { using (StreamReader sr99 = new StreamReader(stream)) { responseContent = sr99.ReadToEnd(); } } } MessageBox.Show(responseContent); 

See username= and &password= for formatting mail data.

You can check it out on fiddle .

Edit:

It seems that your PHP script has parameters named as strongly as those used in your question.

+7
source

All Articles