I am attempting to call a RestResource HttpPost method, but receive an INVALID_SESSION_ID response.
[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}] Apex Code (version 43):
@RestResource(urlMapping='/CustomResourceName/*') global with sharing class CustomResourceClass { @HttpGet global static string doGet() { return 'Success'; } @HttpPost global static string doPost() { return 'Success'; } } When I call the Get method, "Success" is returned.
My Get call:
var reportUri = string.Format("{0}/services/apexrest/CustomResourceName/{1}", instanceUrl, "ID"); HttpWebRequest http = (HttpWebRequest)WebRequest.Create(reportUri); http.Method = "GET"; http.ContentType = "application/json"; http.Headers.Add("Authorization", "Bearer " + accessToken); When I attempt the Post method, I receive the invalid session message.
Post Call:
var reportUri = string.Format("{0}/services/apexrest/CustomResourceName/{1}", instanceUrl, "ID"); HttpWebRequest http = (HttpWebRequest)WebRequest.Create(reportUri); http.Method = "POST"; var json = "{\"Test\": \"Me\"}"; byte[] postBuffer = Encoding.UTF8.GetBytes(json); http.ContentLength = postBuffer.Length; http.ContentType = "application/json"; using (Stream postData = http.GetRequestStream()) { postData.Write(postBuffer, 0, postBuffer.Length); } http.Headers.Add("Authorization", "Bearer " + accessToken); I have tried different signatures for the Post call as well:
@HttpPost global static string doPost(RestRequest req) { return 'Success'; } and
@HttpPost global static string doPost(string theId, string thePostData) { return 'Success'; } I believe it may be the same as this unanswered question.
EDIT: I was able to get the method to accept my Post by updating the Content Type to "application/text" and changing the post data from Json to a string that is not Json.
Updated Code: var reportUri = string.Format("{0}/services/apexrest/CustomResourceName/{1}", instanceUrl, "ID");
HttpWebRequest http = (HttpWebRequest)WebRequest.Create(reportUri); http.Method = "POST"; var json = "{\"Test\": \"Me\"}"; byte[] postBuffer = Encoding.UTF8.GetBytes("Json=" + json); http.ContentLength = postBuffer.Length; http.ContentType = "application/text"; using (Stream postData = http.GetRequestStream()) { postData.Write(postBuffer, 0, postBuffer.Length); } http.Headers.Add("Authorization", "Bearer " + accessToken); How can I make this method work without appending "Json=" to the post body?