2011-08-24 108 views
0

我正在研究WCF REST API集成,也是我第一次與Twitter API合作。我在控制檯應用程序中編寫這些行。請從這裏找到幫助文檔Twitter DocWCF REST for Twitter授權

HttpClient http = new HttpClient("http://twitter.com/statuses/"); 
http.TransportSettings.Credentials = new NetworkCredential(username, password); 
HttpResponseMessage resp = null; 
System.Net.ServicePointManager.Expect100Continue = false; 

Console.WriteLine("\nPlease enter a command: "); 
string command = Console.ReadLine(); 

while (!command.Equals("q")) 
{ 
    try 
    { 
     switch (command) 
     { 
      case "ls public": 
       GetStatuses(http, "public_timeline.xml"); 
       break; 
      case "ls friends": 
       GetStatuses(http, "friends_timeline.xml"); 
       break; 
      case "ls": 
       GetStatuses(http, "user_timeline.xml"); 
       break; 

     } 
    } 
    catch (Exception ex) 
    { 
     Console.ForegroundColor = ConsoleColor.Red; 
     Console.WriteLine(ex.Message); 
     Console.ForegroundColor = ConsoleColor.Yellow; 
    } 

    Console.WriteLine("\nPlease enter a command: "); 
    Console.ReadLine(); 
} 

這裏是其他代碼,

static void GetStatuses(HttpClient http, string uri) 
     { 
      HttpResponseMessage resp= http.Get(uri); 
      resp.EnsureStatusIsSuccessful(); 
      DisplayTwitterStatuses(resp.Content.ReadAsXElement()); 
     } 

     static void DisplayTwitterStatuses(XElement root) 
     { 
      var statuses = root.Descendants("status"); 
      foreach (XElement status in statuses) 
      { 
       Console.ForegroundColor = ConsoleColor.Green; 
       Console.Write(status.Element("user").Element("screen_name").Value); 
       Console.ForegroundColor = ConsoleColor.Gray; 
       Console.Write(" {0} ",status.Element("id").Value); 
       Console.ForegroundColor = ConsoleColor.White; 
       string text = status.Element("text").Value; 
       if (text.Length > 50) 
        text = text.Remove(50) + "...."; 

       Console.WriteLine(text); 
       Console.ForegroundColor = ConsoleColor.Yellow; 

      } 

     } 

如果我選擇「LS公衆」它顯示公衆XML DATAM,但如果我選擇「LS朋友」或「 ls「,即使我的憑證有效,也會拋出授權錯誤。

Unauthorized (401) is not one of the following: OK (200), Created (201), Accepted (202), NonAuthoritativeInformation (203), NoContent (204), ResetContent (205), PartialContent (206) 

請幫我找出解決方案!

+0

你有沒有找到一個解決辦法? 我也有這個具體問題。 我覺得我們需要通過trow頭access_key基於Oauth認證過程 – Silagy

+2

感謝silagy,但我仍然面臨這個問題。 – Sujit

回答

0

爲了從Twitter或其他供應商(谷歌..)您需要提供基於Oauth 1.0 or 2.0

查看Twitter的Authentication documentation

安全權限進行的事情容易,可以幫助Matlus basic library獲取信息See code project on google

他們提供了很好的例子。我用它和成功。

基本上你需要流向那些STAPS

  1. 在Twitter上註冊您的應用程序,並得到客戶的關鍵和客戶祕密密鑰
  2. 在嘰嘰喳喳請參閱授權文件 - link - 見介紹到OAuth
  3. 請求請求令牌
  4. 請求用戶授權
  5. 請求獲取令牌

我的代碼示例使用這個庫

protected void Page_Load(object sender, EventArgs e) 
{ 
    realm = Request.Url.Scheme + "://" + Request.Url.DnsSafeHost + Request.ApplicationPath; 

    if (!IsPostBack) 
    { 
     if (Request.QueryString["oauth_token"] ==null) 
     { 
      MakeRequestForToken(); 
     } 
     else 
     { 
      HandleAuthorizeTokenResponse(); 
     } 
    } 



} 

private void MakeRequestForToken() 
{ 
    string consumerKey = null; 
    string consumerSecret = null; 
    string requestTokenEndpoint = null; 
    string requestTokenCallback = null; 
    string authorizeTokenUrl = null; 

    consumerKey = "my customer key"; 
    consumerSecret = "my customer secret key"; 

    //Twitter 
    requestTokenEndpoint = "https://api.twitter.com/oauth/request_token"; 

    requestTokenCallback = GetRouteableUrlFromRelativeUrl("oAuthGoolgecsSharp/GoogleOauthTry.aspx"); 


    //Twitter 
    authorizeTokenUrl = "https://api.twitter.com/oauth/authorize"; 


    if (String.IsNullOrEmpty(consumerKey) || String.IsNullOrEmpty(consumerSecret)) 
     throw new ArgumentException("Please set up your consumer key and consumer secret for the selected provider", "consumerKey or consumerSecret"); 

    // Step 1: Make the call to request a token 
    var oAuthConsumer = new OAuthConsumer(); 
    var requestToken = oAuthConsumer.GetOAuthRequestToken(requestTokenEndpoint, realm, consumerKey, consumerSecret, requestTokenCallback); 
    PersistRequestToken(requestToken); 

    // Step 2: Make a the call to authorize the request token 
    Response.Redirect(authorizeTokenUrl + "?oauth_token=" + requestToken.Token); 
} 

/// <summary> 
/// Step 3: Exchange the Request Token for an Access Token 
/// </summary> 
private void HandleAuthorizeTokenResponse() 
{ 
    string consumerKey = null; 
    string consumerSecret = null; 
    string accessTokenEndpoint = null; 
    string token = null; 
    string verifier = null; 

    provider = "Google"; 

    token = Request.QueryString["oauth_token"]; 
    verifier = Request.QueryString["oauth_verifier"]; 
    //Google 
    //accessTokenEndpoint = "https://www.google.com/accounts/OAuthGetAccessToken"; 

    //Twitter 
    accessTokenEndpoint = "https://api.twitter.com/oauth/access_token"; 

    if (String.IsNullOrEmpty(consumerKey) || String.IsNullOrEmpty(consumerSecret)) 
     throw new ArgumentException("Please set up your consumer key and consumer secret for the selected provider", "consumerKey or consumerSecret"); 

    // Exchange the Request Token for an Access Token 
    var oAuthConsumer = new OAuthConsumer(); 
    var accessToken = oAuthConsumer.GetOAuthAccessToken(accessTokenEndpoint, realm, consumerKey, consumerSecret, token, verifier, GetRequesttoken().TokenSecret); 
    this.SaveAccessTokken(accessToken); 
    Response.Redirect("~/TaksList.aspx"); 
} 

RequestToken GetRequesttoken() 
{ 
    var requestToken = (RequestToken)Session["RequestToken"]; 
    Session.Remove("RequestToken"); 
    return requestToken; 
} 

void PersistRequestToken(RequestToken requestToken) 
{ 
    Session["RequestToken"] = requestToken; 
} 

string GetRouteableUrlFromRelativeUrl(string relativeUrl) 
{ 
    var url = HttpContext.Current.Request.Url; 
    return url.Scheme + "://" + url.Authority + VirtualPathUtility.ToAbsolute("/" + relativeUrl); 
} 

private void SaveAccessTokken(AccessToken tokken) 
{ 
    Session.Add("AccessTokken",tokken); 
} 
  1. 使Web請求 - 例如http://api.twitter.com/1/statuses/home_timeline.json
  2. 使用使用OAuthUtils.cs與OauthBase.cs
  3. 生成Authorization頭生成簽名方法調用GetUserInfoAuthorizationHeader
  4. 將授權放入請求標頭
  5. 發送請求並獲得數據

見我的代碼示例 私人的accessToken _accessToken = NULL;

protected void Page_Load(object sender, EventArgs e) 
{ 
    _accessToken = (AccessToken)Session["AccessTokken"]; 
    string _customerkey = "my customer key"; 
    string _customerSecret = "my customer secret key"; 


    string nostring = ""; 
    string nnString = ""; 
    OAuthBase oauth = new OAuthBase(); 

    //Twitter 
    Uri t = new Uri("http://api.twitter.com/1/statuses/home_timeline.xml"); 
    string u = oauth.GenerateSignature(t, _customerkey, _customerSecret, _accessToken.Token, 
             _accessToken.TokenSecret, "GET", oauth.GenerateTimeStamp(), 
             oauth.GenerateNonce(), out nostring, out nnString); 

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(nostring); 
    request.Method = "GET"; 


    string realm = Request.Url.Scheme + "://" + Request.Url.DnsSafeHost + Request.ApplicationPath; 

    OAuthUtils util = new OAuthUtils(); 
    AuthorizeHeader h = util.GetUserInfoAuthorizationHeader(t.ToString(), realm, _customerkey, _customerSecret, 
               _accessToken.Token, _accessToken.TokenSecret, 
               SignatureMethod.HMACSHA1, "GET"); 

    request.Headers.Add("Authorization",h.ToString()); 
    Response.Write(request.Headers["Authorization"].ToString() + "<br />"); 

    try 
    { 
     WebResponse response = request.GetResponse(); 
     StreamReader reader = new StreamReader(response.GetResponseStream()); 
     string responseString = reader.ReadToEnd(); 
     reader.Close(); 
     Response.Write(responseString); 
    } 
    catch (Exception ex) 
    { 
     Response.Write(ex.ToString()); 
     //throw; 
    } 





}