使用WP7中的webReuest与Rest APi POST json [英] POST json with Rest APi using webReuest from WP7

查看:103
本文介绍了使用WP7中的webReuest与Rest APi POST json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Rest API更新force.com上的数据库表.而且我正在发布json数据来像这样更新db表.

I am updating the db table on force.com using Rest API. And i am posting json data to update db table like this.

     // preparing webrequest
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

      // adding request headers
      request.ContentType = "application/json";
      request.Headers["Authorization"] = "OAuth " + token;
      request.Headers["X-PrettyPrint"] = "1";
      // request method
      request.Method = "PATCH";
       // start the asynchronous operation
                request.BeginGetRequestStream(new AsyncCallback(SaveBeginGetRequestStreamCallBack), request);


 private void SaveBeginGetRequestStreamCallBack(IAsyncResult ar)
        {

            HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;

            Stream postStream = webRequest.EndGetRequestStream(ar);

            (using (StreamWriter sw = new StreamWriter(postStream))
            {
                 sw.Write(postData);
                // postData is in json format like: {"Name":"Michel"}  
            }

           postStream.close(); 
            webRequest.BeginGetResponse(new AsyncCallback(SaveBeginGetResponseCallback), webRequest);
        }

        private void SaveBeginGetResponseCallback(IAsyncResult ar)
        {

            try
            {
                HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;
                HttpWebResponse response;

                // End the get response operation
                response = (HttpWebResponse)webRequest.EndGetResponse(ar);
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(streamResponse);
                string Response = streamReader.ReadToEnd();
                streamResponse.Close();
                streamReader.Close();
                response.Close();

            }
            catch (WebException e)
            {
                MessageBox.Show(e.Message);
                // Error treatment

            }

但是显示错误的请求错误.这是通过http请求发送json格式的正确方法.

But it is showing bad request error. Is it a right way to send json format over http request.

推荐答案

您不会在调用BeginGetResponse之前关闭/处置postStream ...

You are not closing/disposing the postStream prior to calling BeginGetResponse ...

另外,致电

sw.Write(data);

由于数据是字符串.您的调用(传递偏移量和计数)将适合于字节数组.您实际上是在调用格式超载 http://msdn .microsoft.com/en-us/library/fd857wct(v = VS.96).aspx

Since data is a string. Your call (passing an offset and a count) would be appropriate for a byte array. You are actually calling a formatting overload http://msdn.microsoft.com/en-us/library/fd857wct(v=VS.96).aspx

这篇关于使用WP7中的webReuest与Rest APi POST json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆