7

我正在使用以下代码返回不记名令牌,但我不断收到

“远程服务器返回错误:(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();

任何建议都会很棒

4

2 回答 2

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();
于 2013-06-13T00:47:38.147 回答
1

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

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

如果您需要示例或需要什么,请告诉我。

于 2013-05-22T10:59:49.840 回答