Dwight
Dwight

Reputation: 12480

WebClient.UploadStringAsync does not POST data to the server correctly

I am trying to post an email address and password to a server in order to receive JSON back. However the following code receives a response from the server indicating that the POST data was not received.

private void BtnSignIn_Click(object sender, RoutedEventArgs e)
{
    String email = Email.Text;
    String password = Password.Password;

    String data = "email=" + email + "&password=" + password;

    WebClient wc = new WebClient();
    Uri uri = new Uri("http://api.server.com/login");

    wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
    wc.UploadStringAsync(uri, "POST", data);
}

The string data is produced correctly in the format [email protected]&password=hunter2.

And the event handler function...

private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
    MessageBox.Show(e.Result);
}

What do I need to do to ensure the fields are posted to the server correctly? Thanks!

Upvotes: 2

Views: 3533

Answers (1)

Amit Sharma
Amit Sharma

Reputation: 36

You need to add wc.Headers["Content-Type"] = "application/x-www-form-urlencoded"; and wc.Encoding = Encoding.UTF8; in your code. This will post your data to server correctly. See below code this will help u...

private void BtnSignIn_Click(object sender, RoutedEventArgs e)
{
    String email = Email.Text;
    String password = Password.Password;
    String data = "email=" + email + "&password=" + password;
    WebClient wc = new WebClient();
    Uri uri = new Uri("http://api.server.com/login");
    wc.UploadStringCompleted += new ploadStringCompletedEventHandler(wc_UploadStringCompleted);
    wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
    wc.Encoding = Encoding.UTF8;
    wc.UploadStringAsync(uri, "POST", data);
}

Upvotes: 2

Related Questions