2011-08-24 113 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; 
    } 





}