C#Twitter请求OAuth令牌

时间:2016-09-02 08:27:40

标签: c# twitter oauth

我正在尝试根据我的消费者密钥和消费者密钥从Twitter API请求令牌。但是我得到The remote server returned an error: (403) Forbidden,我不知道为什么?

这是我到目前为止的尝试

//Get Request Token
string oauth_consumer_key = "<consumer key>";
string oauth_consumer_secret = "<consumer secret>";

Uri requestToken = new Uri("https://api.twitter.com/oauth2/token?oauth_consumer_key=" + oauth_consumer_key + "&oauth_consumer_secret=" + oauth_consumer_secret);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requestToken);
req.Method = "POST";

try
{
  using (var response = req.GetResponse() as HttpWebResponse)
  if (req.HaveResponse && response != null)
  {

  }
}
catch (WebException wex)
{
}

代码不完整但是通过它我似乎总是得到Forbidden异常?

如果我按如下方式发布URL请求,它可以正常工作并返回令牌

https://twitter.com/oauth/request_token?oauth_consumer_key=bidjtABOkF0b3mvw1UaHWDf7x&oauth_consumer_secret=qWO208QapZvckBoyWu3QET8uFnBXXlG3tSTWSS8oAOtoY8qwHD

我做错了吗?

1 个答案:

答案 0 :(得分:0)

通过使用Task / Asyc并添加授权OAuth标头解决了我的问题。现在能够获得访问令牌

这是我的解决方案:

public async Task<ActionResult> AccessToken()
{                       
      var httpClient = new HttpClient();
      var request = new HttpRequestMessage(HttpMethod.Post, "https://api.twitter.com/oauth2/token");

      string oauth_consumer_key = "<consumer key>";
      string oauth_consumer_secret = "<consumer secret>";

      string url = "https://api.twitter.com/oauth2/token?oauth_consumer_key=" + oauth_consumer_key + "&oauth_consumer_secret=" + oauth_consumer_secret;

      var customerInfo = Convert.ToBase64String(new UTF8Encoding()
                          .GetBytes(oauth_consumer_key + ":" + oauth_consumer_secret));

     // Add authorization to headers
      request.Headers.Add("Authorization", "Basic " + customerInfo);
      request.Content = new StringContent("grant_type=client_credentials", Encoding.UTF8,
                                                          "application/x-www-form-urlencoded");

      HttpResponseMessage response = await httpClient.SendAsync(request);

      string json = await response.Content.ReadAsStringAsync();
      var serializer = new JavaScriptSerializer();
      dynamic item = serializer.Deserialize<object>(json);

      ViewBag.access_token = item["access_token"];

      return View();            
    }