Twitter API无效或过期令牌

时间:2016-02-13 15:58:35

标签: c# model-view-controller twitter restsharp

我正在尝试使用下面的代码但由于某种原因我收到了一个无效或过期的令牌,它似乎只运行了一次,但再也没有了。

有什么想法吗? (consumerKey和consumerSecret是类中生成的常量。)

    public ActionResult Index()
    {
        string twitterAccount = System.Configuration.ConfigurationManager.AppSettings["twitterAccount"];
        JsonDeserializer jsonDeserializer = new JsonDeserializer();
        var model = new TwitterVM.LandingModel();

        var qs = GetToken();
        string oauthToken = qs["oauth_token"];
        string oauthTokenSecret = qs["oauth_token_secret"];

        RestClient client = new RestClient("https://api.twitter.com/1.1")
        {
            Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, oauthToken, oauthTokenSecret)
        };
        RestRequest request = new RestRequest("statuses/user_timeline", Method.GET);

        request.Parameters.Add(new Parameter()
        {
            Name = "screen_name",
            Value = twitterAccount,
            Type = ParameterType.GetOrPost
        });

        request.Parameters.Add(new Parameter()
        {
            Name = "count",
            Value = 10,
            Type = ParameterType.GetOrPost
        });

        request.Parameters.Add(new Parameter()
        {
            Name = "include_rts",
            Value = true,
            Type = ParameterType.GetOrPost
        });

        request.Parameters.Add(new Parameter()
        {
            Name = "include_entities",
            Value = true,
            Type = ParameterType.GetOrPost
        });

        IRestResponse response = client.Execute(request);

        model.Tweets =
          jsonDeserializer.Deserialize<List<TwitterVM.Tweet>>(response);

        return View(model);
    }


    private NameValueCollection GetToken()
    {
        RestClient client = new RestClient("https://api.twitter.com") { Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret) };
        //Do the auth shit...
        RestRequest request = new RestRequest("oauth/request_token", Method.POST);
        IRestResponse response = client.Execute(request);

        return HttpUtility.ParseQueryString(response.Content);
    }

1 个答案:

答案 0 :(得分:1)

使用Twitter的OAuth2 API( https://api.twitter.com/oauth2/token

有关详细信息,请参阅https://dev.twitter.com/oauth/application-only

var client = await CreateHttpClient("....", "....");
//don't dispose this client and use for subsequent API calls

var screenName = "....";
var count = 10;
var include_rts = true;
var url = $"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={screenName}&include_rts={include_rts}&count={count}";

var json = await client.GetStringAsync(url);
public static async Task<HttpClient> CreateHttpClient(string consumerKey, string consumerSecret)
{
    var bearerToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(consumerKey + ":" + consumerSecret));
    string url = "https://api.twitter.com/oauth2/token";


    HttpClient client = new HttpClient();

    client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Basic " + bearerToken);

    var resp = await client.PostAsync(url, new StringContent("grant_type=client_credentials", Encoding.UTF8, "application/x-www-form-urlencoded")).ConfigureAwait(false);
    resp.EnsureSuccessStatusCode();
    var result = await resp.Content.ReadAsStringAsync().ConfigureAwait(false);
    var jObj = new JavaScriptSerializer().Deserialize<Dictionary<string,string>>(result);

    if (jObj["token_type"] != "bearer") throw new Exception("Invalid Response From Twitter/OAuth");

    client.DefaultRequestHeaders.Remove("Authorization");
    client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + jObj["access_token"]);
    return client;
}