7

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

1

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.

10

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();
  • 1
    this helped me out with my problem, though i'm not using C#/.Net. – the0ther Jun 13 '13 at 16:48

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.