JSON POST不能使用Windows Phone 7

时间:2012-04-20 12:35:43

标签: json silverlight windows-phone-7 post

我不认为这是有效的,我想知道你是否可以发现我的代码有什么问题,我可以解决它吗?我很新,并不确定是否使用Web请求,Web响应或任何东西。什么是对json进行POST的最基本方式?

谢谢

private void btnSaveCar_Click(object sender, RoutedEventArgs e)
        {
            string url = "http://......";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.BeginGetRequestStream(new AsyncCallback(ProcessResponse), request);
        }



    private void ProcessResponse(IAsyncResult asyncResult)
    {
        HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
        Stream streamResp = request.EndGetRequestStream(asyncResult);
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Car));
        Car newCar = new Car():

        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {

            newCar.Condition = txtCondition.Text;
            newCar.Colour = txtColour.Text;
            newCar.RegistrationNumber = txtReg.Text;
            newCar.Model = txtModel.Text;
            short.TryParse(txtYear.Text, out newCar.Year);
            short chassisNumber;
            short.TryParse(txtChassisNumber.Text, out chassisNumber);
            newCar.ChassisNumber = chassisNumber;
            newCar.BodyStyle = txtBodyStyle.Text;
            try
            {
                ser.WriteObject(streamResp, newCar);
                NavigationService.GoBack();
            }
            catch
            {
                MessageBox.Show("didnt work :(");
            }


        });
    }

1 个答案:

答案 0 :(得分:1)

您的代码不完整,您应该在将数据写入请求流后调用Request.BeginGetResponse()方法!

关于如何使用WebRequest进行POST,请查看this sample code(请注意该示例适用于.NET 4.0但我认为您会明白这一点。)

我仍然建议您使用RestSharp而不是使用基本的WebRequest来节省一些开发时间!