我正在尝试将电子邮件地址和密码发布到服务器以便接收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);
}
我需要做些什么来确保字段正确发布到服务器?谢谢!
答案 0 :(得分: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);
}