Last active
December 13, 2020 14:26
-
-
Save tiagonmas/f728647dce06c1a549ccdee1357e10a4 to your computer and use it in GitHub Desktop.
Call a particle.io function (http post with application/x-www-form-urlencoded) in c# / Xamarin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public async Task<ParticleFunctionReturn> CallParticleFunction(ParticleFunction pFunc) | |
{ | |
ParticleFunctionReturn pfRet = new ParticleFunctionReturn(); | |
try | |
{ | |
Uri uri = new Uri(string.Format(baseUrl, pFunc.DeviceId, pFunc.FuncName)); | |
Uri pfuri = new Uri(string.Format(baseUrl, pFunc.DeviceId, pFunc.FuncName)); | |
FormUrlEncodedContent postData = new FormUrlEncodedContent( | |
new List<KeyValuePair<string, string>> | |
{ | |
new KeyValuePair<string, string>("arg", pFunc.Args) | |
} | |
); | |
var requestMessage = new HttpRequestMessage | |
{ | |
Method = HttpMethod.Post, | |
Content = postData, | |
RequestUri = pfuri | |
}; | |
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", pFunc.Token); | |
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header | |
HttpResponseMessage response = await client.SendAsync(requestMessage); | |
if (response.IsSuccessStatusCode) | |
{ | |
string content = await response.Content.ReadAsStringAsync(); | |
pfRet = JsonConvert.DeserializeObject<ParticleFunctionReturn>(content); | |
pfRet.Error = false; | |
} | |
else | |
{ | |
pfRet.Error = true; | |
pfRet.ErrorDetail = response.ToString(); | |
} | |
} | |
catch (Exception ex) | |
{ | |
//To Do | |
throw (ex); | |
} | |
return pfRet; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment