Twitter look api 401 error - twitter

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.

Related

getting error "unsupported_grant_type" on calling Xero refresh token api

I am working with Xero Api for fetching invoices data. when my access token get expired i try to generate new via refresh token but getting unsupported_grant_type as response.
Below is my Refresh token request
var client = new RestClient("https://identity.xero.com/connect/token?=");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("grant_type", "refresh_token");
// request.AddParameter("grant_type", "authorization_code");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
string plainText = "2C707E29C627444EA73AADB3F0E7448A" + ":" + "6iUQ0NyBBXpDpSKYaprvowUjXAif41uK1QHCtyBL3vArPotc";
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
string encodedText = Convert.ToBase64String(plainTextBytes);
request.AddHeader("Authorization", "Basic "+ encodedText);
request.AddHeader("Cookie", "Device=ac903639876241ba992f5170c176d7b7; _abck=12ACF4E93634D401FB7C7CD9B544788F~-1~YAAQDhwgFxmkCKxxAQAABPlOxwN07cMPzGAXcBjZYifvWgfzqqRd3uABVwuMX4OdtZPCU0OwcOkalVuQuFLUD3PNpJVe+bNkVZ45qWTjNW6gBhBiC2TUGZCQiSLekeP6HnbVkMZRZtepwUWgnTjCQ5/XWPJOchHM/ecE4rwA4xYMEy7emjMAolOGX8X5u70+R8xdVkZlj8YBk4NkeMglm6y1JVhTt/nq6SDGXBS34vAJD8T/68WZKCLVOSem/nJe8NUdShIjRWL+yRA2Pb1o+HobR3DJbsmlIe0ezy8SqgQAkLTBhdZjHw==~-1~-1~-1; ak_bmsc=FA12D3F371BC6D88443778C8FE9E2CB517D46377B84C00002455AA5EDBC7DA24~plR4FZN8ha50tsVyXSR+JkZ3uSvHbHVfTiQnq35HFaGEy2UHAuhq6dv5vGqV00GaFPoP70p2Dsf7Bc0aodRmJZcwU9N4vEcRrqbBVHV/5DOQF/eTLHXALoJDFc3esQx+Kz0EipR3u6eyG7sasDKtIiaOZp+xJ1Zx6SNQjeXzPrHE+3HszFaTVzRoblzkGcevuxAL7dsQEkrp4uB20CIU9OaXdjaHV4UaigOGlSsYo5nt4=; bm_sz=449A6535155E672AF783F7717001BF49~YAAQd2PUFzOmXshxAQAAG5VcyQfeizXKc2d1vZwMBqcVRnfmYnCrLBU2iaDaFofTIDWTr7FeK1nADuceBhikxVF3tXWeHSTOLkYULwIHuz7fioBZC7wPf03kJYMapENDooKz8n5z++a+s4N0JT2jXcZTVkdYDgbr6FG3ErOgZGTaGXbywmZs8Ze7pHPK; bm_sv=0D600B86F31575226013DBA1C988C3D0~9oZEcht4TxX7Vc9IjcjPiD/9Y4vNQqaHwgePlGWuiQ93Upjk156QtA/Yfv6WFvtxFQ5i7jO+EK/pFrb/1mdJpIlqbIHgamHN6mGCVsuFYE/vGbC5+pl9j3pPVtjv41yJjL4KnmUNSsbCT+JEhYIfEg==");
request.AlwaysMultipartFormData = true;
request.AddParameter("grant_type", "refresh_token");
request.AddParameter("refresh_token", "04ed7e45fa36f0fc753257b0259a73c43e1effffbb8c588e00f0d5b262a39264");
request.AddParameter("client_id", "2C707E29C627444EA73AADB3F0E7448A");
request.AddParameter("client_secret", "6iUQ0NyBBXpDpSKYaprvowUjXAif41uK1QHCtyBL3vArPotc");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
dynamic data = JsonConvert.DeserializeObject(response.Content);
AccessToken = data.access_token;

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

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();

Discogs api oauth: authenticate/identity

I'm trying to build a .net program that helps me organizing my vinyls. For that I use the discogs API. I'm having problems with the oauth procedure. The first 4 steps were succesful; I received an access_token and access_token_secret (using the request_token, request_token_secret and verifier). Only the last step is giving me problems: the identity check to see if I (the user) am succesfully authorized. According to the discogs APi documentation it should be enought to send the access_token and access_token_secret to /oauth/identity but I keep getting a '502 bad gateway' response.
This is the request I send:
Public Function makeTestRequest()
Dim requestResult As String = ""
Dim user_agent As String = "ll// .01 DiscogsTestApp"
Dim oauth_consumer_key As String = "AAA"
Dim oauth_token As String = "BBB"
oauth_signature_method = "PLAINTEXT"
Dim oauth_signature As String = "CCC&" & "DDD"
oauth_timestamp = setTimeStamp()
oauth_nonce = setNounce()
'Set authorization header
Dim headerFormat As String = "OAuth oauth_consumer_key=""{0}"",oauth_nonce=""{1}"",oauth_token""{2}"",oauth_signature""{3}"",oauth_signature_method""{4}"",oauth_timestamp""{5}"""
'Dim authHeader As String = String.Format(headerFormat, Uri.EscapeDataString(oauth_consumer_key), Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_signature), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp), Uri.EscapeDataString(oauth_token), Uri.EscapeDataString(oauth_version))
'set the request
ServicePointManager.Expect100Continue = False
Dim request As HttpWebRequest
Dim response As HttpWebResponse
Dim streamReader As System.IO.StreamReader
Dim encode As Encoding = System.Text.Encoding.GetEncoding("utf-8")
Dim requestUrl3 As String = "http://api.discogs.com/oauth/identity"
request = WebRequest.Create(requestUrl3)
request.Accept = "application/json, text/plain, */*"
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = 0
request.Method = "GET"
request.UserAgent = "user_agent"
request.Timeout = -1
request.Headers.Add("Authorization", authHeader)
Try
response = DirectCast(request.GetResponse, HttpWebResponse)
streamReader = New System.IO.StreamReader(response.GetResponseStream(), encode)
requestResult = streamReader.ReadLine
request.Abort()
streamReader.Close()
streamReader = Nothing
response.Close()
response = Nothing
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
Return requestResult
End Function
As you see I send more than just access_token and secret (according to this example)
So this keeps giving me a '502 bad gateway' response... Does anyone have an idea what is causing this? Perhaps any ideas that I can try?
Just for info: the post request for requesting access_token works fine, here is the code:
Public Function makeFinalRequest()
Dim requestResult As String = ""
oauth_nonce = setNounce()
oauth_timestamp = setTimeStamp()
Dim oauth_signature As String = Form1.txtconsumer_secret.Text & Form1.txtoauth_token_secret.Text
oauth_consumer_key = Form1.txtconsumer_key.Text
oauth_signature_method = "PLAINTEXT"
Dim oauth_token As String = Form1.txtoauth_token.Text
Dim oauth_verifier As String = Form1.txtverifier.Text
Dim user_agent As String = "ll// .01 DiscogsTestApp"
oauth_token_secret = Form1.txtoauth_token_secret.Text
Dim oauth_version As String = "1.0"
'Set authorization header
Dim headerFormat As String = "OAuth oauth_consumer_key=""{0}"", oauth_nonce=""{1}"",oauth_token=""{2}"",oauth_signature=""{3}"",oauth_signature_method=""{4}"",oauth_timestamp=""{5}"",oauth_verifier=""{6}"",oauth_version=""{7}"""
Dim authHeader As String = String.Format(headerFormat, Uri.EscapeDataString(oauth_consumer_key), Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_token), Uri.EscapeDataString(oauth_signature), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp), Uri.EscapeDataString(oauth_verifier), Uri.EscapeDataString(oauth_version))
'set the request
ServicePointManager.Expect100Continue = False
Dim request As HttpWebRequest
Dim response As HttpWebResponse
Dim streamReader As System.IO.StreamReader
Dim encode As Encoding = System.Text.Encoding.GetEncoding("utf-8")
Dim requestUrl2 As String = "https://api.discogs.com/oauth/access_token"
request = WebRequest.Create(requestUrl2)
request.UserAgent = user_agent
request.Accept = "application/json, text/plain, */*"
request.Method = "POST"
'request.ContentLength =
request.Timeout = -1
request.ContentLength = 0
request.Headers.Add("Authorization", authHeader)
Try
response = DirectCast(request.GetResponse, HttpWebResponse)
streamReader = New System.IO.StreamReader(response.GetResponseStream(), encode)
requestResult = streamReader.ReadLine
request.Abort()
streamReader.Close()
streamReader = Nothing
response.Close()
response = Nothing
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
Return requestResult
End Function
Please let me know if I need to post more details...
Any help is much appreciated!
Thanks

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 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).

Resources