POST json with Rest APi 使用 webReuest 来自 WP7
本文关键字:webReuest 来自 WP7 使用 APi json with Rest POST | 更新日期: 2023-09-27 17:56:08
我正在使用 Rest API 更新 force.com 上的数据库表。我正在发布 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
}
但它显示错误的请求错误。这是通过http请求发送json格式的正确方法吗?
在调用 BeginGetResponse 之前,您没有关闭/处置 postStream ...
另外,致电
sw.Write(data);
由于数据是一个字符串。您的调用(传递偏移量和计数)适用于字节数组。 您实际上是在调用格式化重载 http://msdn.microsoft.com/en-us/library/fd857wct(v=VS.96).aspx