使用twitter获取持有者令牌

时间:2013-05-21 17:27:15

标签: twitter oauth oauth-2.0 twitter-oauth

我正在使用以下代码返回持票人令牌,但我一直在

“远程服务器返回错误:(500)内部服务器错误”在线 “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();

任何建议都会很棒

2 个答案:

答案 0 :(得分:10)

我浪费了很多时间后找到了解决方案。 由于使用Unicode的base64编码,此错误将上升。只需将UNICODE更改为UTF8即可。

最终代码:

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 :(得分:1)

过去我曾使用Twitter的1.1 API的TweetSharp。你可能会更好地将它用于你的推特电话。

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

如果您需要示例或您需要的内容,请与我们联系。