Send an HTTP POST request with C#

48,433

It's because you need to assign your posted parameters with the = equal 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 the username= and &password= in post data formatting.

You can test it on this fiddle.

Edit :

It seems that your PHP script has parameters named diffently than those used in your question.

Share:
48,433
abdallah
Author by

abdallah

Updated on September 22, 2020

Comments

  • abdallah
    abdallah over 3 years

    I'm try to Send Data Using the WebRequest with POST But my problem is No data has be streamed 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 the result

  • abdallah
    abdallah about 8 years
    I try it But Still the same problem
  • Fabien ESCOFFIER
    Fabien ESCOFFIER about 8 years
    I updated my answer. I also added a fiddle so you can test yourself, it does work.
  • Fabien ESCOFFIER
    Fabien ESCOFFIER about 8 years
    It's because your PHP script accept parameters that are named differently thant you exposed in your question.
  • Fabien ESCOFFIER
    Fabien ESCOFFIER about 8 years
    What are the parameters name that your PHP script use ?
  • abdallah
    abdallah about 8 years
    How I Can make it without adding "=&Login=Login" ?
  • Fabien ESCOFFIER
    Fabien ESCOFFIER about 8 years
    It seems your issue come from your PHP script, as you can see the fiddle work.