Send a message using WebRequest and Twilio

I need to send a message using Twilio and NetDuino services. I know that there is an API that allows you to send messages, but it uses Rest-Sharp behind a scene that is incompatible with the micro-frame. I am trying to do something like below, but I have error 401 (not authorized). I got this form here (this 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(); 
0
source share
1 answer

Twilio the evangelist is here.

From the above code, it doesn't look like you are replacing the {AccountSid} token in the MessageApiString variable with the actual Sid account.

Also, it looks like you are adding phone number parameters to the URL as request values. Since this is a POST request, I believe that you need to include them as the request body, and not in the request queue, which means that 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 this helps.

+5
source

All Articles