Send Message using a WebRequest and Twilio
Asked Answered
L

1

0

I'm need to send a message using Twilio services and the NetDuino. I know there is an API that allows to send messages but it uses Rest-Sharp behind the scene which is not compatible with the micro-framework. I have try to do something like the below but I got a 401 error (not authorized). I got this code form here (which is exactly what I need to do)

var MessageApiString = "https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/SMS/Messages.json";
var request = WebRequest.Create(MessageApiString + "?From=+442033*****3&To=+447*****732&Body=test");
var user = "AC4*************0ab05bf";
var pass = "0*************b";
request.Method = "POST";
request.Credentials = new NetworkCredential(user, pass);
var result = request.GetResponse();
Lavine answered 30/4, 2014 at 17:54 Comment(1)
Does the Microframework support standard cURL requests? You could use that instead of WebRequest?Till
A
6

Twilio evangelist here.

From the code above it does not look like you are replacing the {AccountSid} token in the MessageApiString variable with your actual Account Sid.

Also, it looks like you are appending the phone number parameters to the URL as querystring values. Because this is a POST request I believe you need to include these as the request body, not in the querystring, which means you also need to set the ContentType property.

Here is an example:

var accountSid = "AC4*************0ab05bf";
var authToken = "0*************b";

var MessageApiString = string.Format("https://api.twilio.com/2010-04-01/Accounts/{0}/SMS/Messages.json", accountSid);

var request = WebRequest.Create(MessageApiString);
request.Method = "POST";
request.Credentials = new NetworkCredential(accountSid, authToken);
request.ContentType = "application/x-www-form-urlencoded";

var body = "From=+442033*****3&To=+447*****732&Body=test";
var data = System.Text.ASCIIEncoding.Default.GetBytes(body);

using (Stream s = request.GetRequestStream())
{
    s.Write(data, 0, data.Length);
}

var result = request.GetResponse();

Hope that helps.

Arabella answered 2/5, 2014 at 17:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.