Twilio send sms api request using http post mentod in asp.net - asp.net-mvc

I am learning twilio send sms tool.
I want to make post url request for send message in asp.net mvc application.
I tired some code but could not get safisfied o/p.
There is an error that is authentication sid or auth token is invalid.
Can anyone help me how to make post request for twilio send sms api?
try{
const string accountSid = "AC255e61580d73904b2a5e5a5e39c715f0";
const string authToken = "AUTH_TOKEN";
const string url = "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/Messages.json";
TwilioRestClient client = new TwilioRestClient(accountSid, authToken);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
var authInfo = accountSid +":"+ authToken;
authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(authInfo));
request.Method = "POST";
var postData = "{\"To\":" + "\"" + sms.ToNumber + "\"" + ", \"From\":" + "\"" + fromNumber + "\"" + ", \"Body\":" + "\"" + sms.Body + "\"}";
var data = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream writer = null;
writer = request.GetRequestStream();
writer.Write(data, 0, data.Length);
writer.Close();
request.Headers["Authorization"] = "Basic " + authInfo;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string content = reader.ReadToEnd();
msg = client.SendMessage("+12012317746 ", sms.ToNumber,sms.Body);
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
string err =reader.ReadToEnd();
}
}
I have an error :
{"code": 20003, "detail": "Your AccountSid or AuthToken was incorrect.", "message": "Authentication Error - No credentials provided", "more_info": "https://www.twilio.com/docs/errors/20003", "status": 401}

Please check if you are using the Live credentials(accountSid,authToken) on your Twilio Account.
The API does the post already:
https://www.twilio.com/docs/api/twiml/sms/twilio_request
You don't need all this code below.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
var authInfo = accountSid +":"+ authToken;
authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(authInfo));
request.Method = "POST";
var postData = "{\"To\":" + "\"" + sms.ToNumber + "\"" + ", \"From\":" + "\"" + fromNumber + "\"" + ", \"Body\":" + "\"" + sms.Body + "\"}";
var data = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream writer = null;
writer = request.GetRequestStream();
writer.Write(data, 0, data.Length);
writer.Close();
request.Headers["Authorization"] = "Basic " + authInfo;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string content = reader.ReadToEnd();

Related

Bad Request model derivative autodesk api when translating dwg to obj format

I want to use autodesk model derivative api to show DWG file in forge viewer. In
result = _client.Execute(objReq);
if (result.StatusCode == System.Net.HttpStatusCode.OK || result.StatusCode==System.Net.HttpStatusCode.Created)
{
}
I get badrequest.
public virtual ActionResult Index()
{
SetupViewer();
if (_bucketFound)
{
//upload file
RestRequest uploadReq = new RestRequest();
uploadReq.Resource = "oss/v2/buckets/"+_bucketName+"/objects/"+_filepath;
uploadReq.Method = Method.PUT;
uploadReq.AddHeader("Content-Type", _fileContentType);
uploadReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
var result= _client.Execute(uploadReq);
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
String responseString = result.Content;
int len = responseString.Length;
int objectKeyIndex = responseString.IndexOf("\"objectKey\" : \"");
int index = responseString.IndexOf("urn:");
responseString = responseString.Substring(index, objectKeyIndex - index-5).Replace("urn:", "").Trim();
_fileUrn = "urn:"+responseString;
//convert urn to base64
string base64Urn = Base64Convertor.Base64Encode(_fileUrn);
// Remove ending '=' signs
// Use _ instead of /
// Use - insteaqd of +
base64Urn = base64Urn.Replace("=", "");
//translate to SVF format
//RestRequest svfReq = new RestRequest();
//svfReq.Resource = "modelderivative/v2/designdata/job";
//svfReq.Method = Method.POST;
//svfReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
//svfReq.AddParameter("Content-Type", "application/json;charset=utf-8", ParameterType.HttpHeader);
//string body = "{\"input\":{\"urn\":\"" + base64Urn + "\",\"compressedUrn\":true,\"rootFilename\":\""+_filepath+ "\"},\"output\":{\"formats\":[{\"type\":\"svf\",\"views\":[\"2d\"]}]}}";
//svfReq.AddParameter("application/json", body, ParameterType.RequestBody);
// translate to OBJ format
RestRequest objReq = new RestRequest();
objReq.Resource = "modelderivative/v2/designdata/job";
objReq.Method = Method.POST;
objReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
objReq.AddParameter("Content-Type", "application/json", ParameterType.HttpHeader);
string body = "{\"input\":{\"urn\":\"" + base64Urn + "\"},\"output\":{\"formats\":[{\"type\":\"obj\"}]}}";
result = _client.Execute(objReq);
if (result.StatusCode == System.Net.HttpStatusCode.OK || result.StatusCode==System.Net.HttpStatusCode.Created)
{
//check the transition complete
RestRequest checkTransitionCompleteGetReq = new RestRequest();
checkTransitionCompleteGetReq.Resource = "modelderivative/v2/designdata/"+base64Urn+"/manifest";
checkTransitionCompleteGetReq.Method = Method.GET;
checkTransitionCompleteGetReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
var result2 = _client.Execute(checkTransitionCompleteGetReq);
if (result2.StatusCode == System.Net.HttpStatusCode.OK)
{
ViewBag.BucketFound = result.Content;
}
}
}
}
return View();
}
void SetupViewer()
{
// Authentication
bool authenticationDone = false;
RestRequest authReq = new RestRequest();
authReq.Resource = "authentication/v1/authenticate";
authReq.Method = Method.POST;
authReq.AddHeader("Content-Type", "application/x-www-form-urlencoded");
authReq.AddParameter("client_id", ConfigurationManager.AppSettings["ClientId"]);
authReq.AddParameter("client_secret", ConfigurationManager.AppSettings["ClientSecret"]);
authReq.AddParameter("grant_type", "client_credentials");
authReq.AddParameter("scope", "bucket:create bucket:read data:write data:read");
IRestResponse result = _client.Execute(authReq);
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
String responseString = result.Content;
int len = responseString.Length;
int index = responseString.IndexOf("\"access_token\":\"") + "\"access_token\":\"".Length;
responseString = responseString.Substring(index, len - index - 1);
int index2 = responseString.IndexOf("\"");
_accessToken = responseString.Substring(0, index2);
//Set the token.
RestRequest setTokenReq = new RestRequest();
setTokenReq.Resource = "utility/v1/settoken";
setTokenReq.Method = Method.POST;
setTokenReq.AddHeader("Content-Type", "application/x-www-form-urlencoded");
setTokenReq.AddParameter("access-token", _accessToken);
IRestResponse resp = _client.Execute(setTokenReq);
if (resp.StatusCode == System.Net.HttpStatusCode.OK)
{
authenticationDone = true;
}
}
if (!authenticationDone)
{
ViewData["Message"] = "View and Data client authentication failed !";
_accessToken = String.Empty;
return;
}
RestRequest bucketReq = new RestRequest();
bucketReq.Resource = "oss/v2/buckets";
bucketReq.Method = Method.POST;
bucketReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
bucketReq.AddParameter("Content-Type", "application/json", ParameterType.HttpHeader);
//bucketname is the name of the bucket.
string body = "{\"bucketKey\":\"" + _bucketName + "\",\"policyKey\":\"transient\"}";
bucketReq.AddParameter("application/json", body, ParameterType.RequestBody);
result = _client.Execute(bucketReq);
if (result.StatusCode == System.Net.HttpStatusCode.Conflict ||
result.StatusCode == System.Net.HttpStatusCode.OK)
{
// _bucketFound = true;
//Check bucket
RestRequest bucketGetReq = new RestRequest();
bucketGetReq.Resource = "oss/v2/buckets";
bucketGetReq.Method = Method.GET;
bucketGetReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
bucketGetReq.AddParameter("Content-Type", "application/json", ParameterType.HttpHeader);
result = _client.Execute(bucketGetReq);
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
_bucketFound = true;
ViewBag.BucketFound = "Found";
}
else
ViewBag.BucketFound = "NotFound";
}
else
{
ViewData["Message"] = "View and Data bucket could not be accessed !";
_bucketFound = false;
return;
}
}
Could you try this again, we had some down time from our side during that time, but everything should be back up and running for you. In case does not work I will take a look at your request.

Oauth2 Yahoo Gemini API

I am having trouble calling Yahoo Gemini API to access Yahoo Gemini Advertising from my C# console (desktop) application.
Here are steps I used:
Create an installed application on https://developer.yahoo.com/apps/create/. This gave me both {Client ID} and {Client Secret}.
https://api.login.yahoo.com/oauth2/request_auth?client_id={Client ID} &redirect_uri=oob&response_type=code&language=en-us. This will take me to the yahoo login screen where I sign in. Press the Agree button and the next screen shows the seven-letter authorization code (say nzbcns9). I write down this authorization code.
Then I use the following code to try to get the access token:
class Program
{
static void Main(string[] args)
{
string clientId = {Client ID};
string secret = {Client Secret};
var request = WebRequest.Create(#"https://api.login.yahoo.com/oauth2/get_token");
request.Method = "POST";
SetBasicAuthHeader(request, clientId, secret);
string postData = "grant_type=authorization_code&redirect_uri=oob&code=nzbcns9";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
request.ContentLength = byte1.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byte1, 0, byte1.Length);
dataStream.Close();
request.ContentType = "application/x-www-form-urlencoded";
var response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
}
static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
}
}
Then I get
Unhandled Exception: System.Net.WebException: The remote server returned an error: (401) Unauthorized. at System.Net.HttpWebRequest.GetResponse().
What did I do wrong?
I also try to post the same message using Fiddler, I get
{"error":"invalid_request"}
I tried your code and what worked for me was to put the line request.ContentType = "application/x-www-form-urlencoded"; BEFORE Stream dataStream = request.GetRequestStream();
So this worked:
string postData = "grant_type=authorization_code&redirect_uri=oob&code=nzbcns9";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
request.ContentLength = byte1.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = request.GetRequestStream();
dataStream.Write(byte1, 0, byte1.Length);
dataStream.Close();
Neither of these worked for me, but it did work once I changed the SetBasicAuthHeader to use ISO-8859-1 encoding:
static void SetBasicAuthHeader( WebRequest request, String userName, String userPassword )
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String( Encoding.GetEncoding( "ISO-8859-1" ).GetBytes( authInfo ) );
request.Headers[ "Authorization" ] = "Basic " + authInfo;
}

Twitter look api 401 error

Below code helped me to implement REST API calls with Twitter
var oauth_token = membership.Token; //"insert here...";
var oauth_token_secret = membership.TokenSecret; //"insert here...";
var oauth_consumer_key = consumerKey;
var oauth_consumer_secret = consumerSecret;
// oauth implementation details
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
// unique request details
var oauth_nonce = Convert.ToBase64String(
new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow
- new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
// create oauth signature
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version
);
baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
"&", Uri.EscapeDataString(oauth_token_secret));
string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oauth_signature = Convert.ToBase64String(
hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
// create the request header
var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
"oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
"oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
"oauth_version=\"{6}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_version)
);
ServicePointManager.Expect100Continue = false;
// make the request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
var response = (HttpWebResponse)request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var objText = reader.ReadToEnd();
return objText.ToString();
But the problem is that when I tried to implement https://api.twitter.com/1.1/statuses/lookup.json?id=20,432656548536401920 api it shows 401 error. The error comes only this api call only.

Twitter streaming api hangs

I was able to get this to run without any error being thrown however after it gets to the line "string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();" it just hangs. I have a breakpoint on the next line and still nothing. Am I not using this correctly? This is in a windows forms application. What do I need to do in order to parse this out? How do I grab the data while keeping the stream open?
My goal with this is to be able to grab tweets and sort them based on criteria TBD.
var oAuthToken = "****";
var oAuthTokenSecret = "****";
var oAuthConsumerKey = "****";
var oAuthConsumerSecret = "****";
var oAuthVersion = "1.0";
var oAuthSignatureMethod = "HMAC-SHA1";
var oAuthNonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oAuthTimeStamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
var resourceURL = "https://stream.twitter.com/1.1/statuses/filter.json";
var locations = "-180,-90,180,90";
var baseFormat = "locations={6}&oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";
var baseString = string.Format(baseFormat,
oAuthConsumerKey,
oAuthNonce,
oAuthSignatureMethod,
oAuthTimeStamp,
oAuthToken,
oAuthVersion,
Uri.EscapeDataString(locations)
);
baseString = string.Concat("POST&", Uri.EscapeDataString(resourceURL), "&", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oAuthConsumerSecret),
"&", Uri.EscapeDataString(oAuthTokenSecret));
string oAuthSignature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oAuthSignature = Convert.ToBase64String(
hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
// create the request header
var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
"oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
"oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
"oauth_version=\"{6}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oAuthNonce),
Uri.EscapeDataString(oAuthSignatureMethod),
Uri.EscapeDataString(oAuthTimeStamp),
Uri.EscapeDataString(oAuthConsumerKey),
Uri.EscapeDataString(oAuthToken),
Uri.EscapeDataString(oAuthSignature),
Uri.EscapeDataString(oAuthVersion)
);
//make the request
ServicePointManager.Expect100Continue = false;
var postBody = "locations=" + Uri.EscapeDataString(locations);
resourceURL += "?" + postBody;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resourceURL);
request.Headers.Add("Authorization", authHeader);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
try
{
WebResponse response = request.GetResponse();
string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
catch (Exception exception)
{
throw (exception);
}
Well it's a streaming API, so it will stream infinitely. Hence if you are trying to read to the end of stream, it will block forever until you run out of memory or get disconnected due to network error etc.
You need to process the data while connected to the stream. If I were you I'd just use a client library (see https://dev.twitter.com/docs/twitter-libraries).

The remote server returned an error: (403) Forbidden. error?

below is my code..I get an error -"The remote server returned an error: (403) Forbidden."..:
TimeSpan t = DateTime.Now - new DateTime(1970, 1, 1);
string content = #"<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:media='http://search.yahoo.com/mrss/'
xmlns:gphoto='http://schemas.google.com/photos/2007' >
<title type='text'>Trip To Italy</title>
<summary type='text'>This was the recent trip I took to Italy.</summary>
<gphoto:location>Italy</gphoto:location>
<gphoto:access>public</gphoto:access>
<gphoto:timestamp>" + t.Milliseconds.ToString() + #"</gphoto:timestamp>
<media:group><media:keywords>italy</media:keywords></media:group>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/photos/2007#album'></category>
</entry>";
ServicePointManager.ServerCertificateValidationCallback = new
RemoteCertificateValidationCallback(delegate(object sender2, X509Certificate
certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
});
string url = "https://www.picasaweb.google.com/data/feed/api/user/default";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/atom+xml";
request.Headers.Add(HttpRequestHeader.Authorization, "AuthSub token=\"" +
Session["token"].ToString() + "\"");
request.Headers.Add("GData-Version", "2.0");
byte[] send = System.Text.UTF8Encoding.UTF8.GetBytes(content);
request.ContentLength = send.Length;
int bytesRead = 0;
Stream requestStream = request.GetRequestStream();
while (send.Length - bytesRead > 1)
requestStream.Write(send, bytesRead++ , 1); //Edited
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string responseStr = responseReader.ReadToEnd();
please help :)
Look at the code
while (send.Length - bytesRead > 1)
requestStream.Write(send, 0, bytesRead++);
Here you're sending the first byte, then the first two, then the first three, and so on. Try the following instead (not tested):
for(int i=0;i<send.Length;i++){
requestStream.Write(send,i,1);
bytesRead++;
}

Resources