[英]POST json with Rest APi using webReuest from WP7
I am updating the db table on force.com using Rest API. 我正在使用Rest API更新force.com上的数据库表。 And i am posting json data to update db table like this.
而且我正在发布json数据来更新这样的数据库表。
// 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
}
But it is showing bad request error. 但是显示错误的请求错误。 Is it a right way to send json format over http request.
这是通过http请求发送json格式的正确方法。
You are not closing/disposing the postStream prior to calling BeginGetResponse ... 您没有在调用BeginGetResponse之前关闭/处理postStream ...
Also, call 另外,打电话
sw.Write(data);
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
您实际上是在调用格式化重载http://msdn.microsoft.com/zh-cn/library/fd857wct(v=VS.96).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.