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.clo开发者_JAVA百科se();
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.
You are not closing/disposing the postStream prior to calling BeginGetResponse ...
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
精彩评论