Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using twitter to get bearer token

I'm using the following code to return the bearer token but i keep getting

"The remote server returned an error: (500) internal server error" on line "WebResponse response = request.GetResponse();"

 WebRequest request = WebRequest.Create("https://api.twitter.com/oauth2/token");

    string consumerKey = "31111111111111111111";
    string consumerSecret = "1111111111111111111111A";
    string consumerKeyAndSecret = String.Format("{0}:{1}", consumerKey, consumerSecret);

    request.Method = "POST";   
    request.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String(Encoding.Unicode.GetBytes(consumerKeyAndSecret))));

    request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";

    string postData = "grant_type=client_credentials";
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    request.ContentLength = byteArray.Length;
    Stream dataStream = request.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();

    WebResponse response = request.GetResponse();

Any advise would be amazing

like image 969
Adam Avatar asked May 21 '13 17:05

Adam


2 Answers

I found the solution after wasting many hours. This error will rise because of the base64 encoding using Unicode. Just change the UNICODE to UTF8, and nothing else.

Final code:

WebRequest request = WebRequest.Create("https://api.twitter.com/oauth2/token");

string consumerKey = "31111111111111111111";
string consumerSecret = "1111111111111111111111A";
string consumerKeyAndSecret = String.Format("{0}:{1}", consumerKey, consumerSecret);

request.Method = "POST";   
request.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(consumerKeyAndSecret))));

request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";

string postData = "grant_type=client_credentials";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

WebResponse response = request.GetResponse();
like image 187
Kousha Avatar answered Nov 15 '22 15:11

Kousha


In the past I have used TweetSharp that uses Twitter's 1.1 API. You'd probably be better using that for your twitter calls.

TweetSharp Github: https://github.com/danielcrenna/tweetsharp

If you require an example or what you need, let me know.

like image 43
sbhomra Avatar answered Nov 15 '22 16:11

sbhomra