2

我正在尝试将电子邮件地址和密码发布到服务器以接收 JSON。但是,以下代码从服务器接收到响应,表明未收到 POST 数据。

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);
}

该字符串data以格式正确生成email=test@test.com&password=hunter2

和事件处理函数...

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

我需要做些什么来确保将字段正确发布到服务器?谢谢!

4

1 回答 1

2

您需要在代码中添加wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";wc.Encoding = Encoding.UTF8;。这会将您的数据正确发布到服务器。请参阅下面的代码,这将帮助您...

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);
}
于 2013-09-21T10:53:47.170 回答