Skip to content

Instantly share code, notes, and snippets.

@tiagonmas
Last active December 13, 2020 14:26
Show Gist options
  • Save tiagonmas/f728647dce06c1a549ccdee1357e10a4 to your computer and use it in GitHub Desktop.
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
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