Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用于Twitter授权的WCF REST_C#_Wcf_Api_Twitter_Wcf Rest - Fatal编程技术网

C# 用于Twitter授权的WCF REST

C# 用于Twitter授权的WCF REST,c#,wcf,api,twitter,wcf-rest,C#,Wcf,Api,Twitter,Wcf Rest,我正在进行WCF REST API集成,这也是我第一次使用Twitter API。我在控制台应用程序中对这些行进行编码。请从这里找到帮助文档 这是其他代码 static void GetStatuses(HttpClient http, string uri) { HttpResponseMessage resp= http.Get(uri); resp.EnsureStatusIsSuccessful();

我正在进行WCF REST API集成,这也是我第一次使用Twitter API。我在控制台应用程序中对这些行进行编码。请从这里找到帮助文档

这是其他代码

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 public”,它将显示公共xml数据m,但如果我选择“ls friends”或“ls”,它将抛出授权错误,即使我的凭据有效

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

请帮我找出解决办法

为了从Twitter或其他提供商(谷歌..)获取信息,您需要基于

查看推特

为了使事情变得简单,你可以帮助

他们提供了很好的例子。我用过它,并取得了成功

基本上,你需要流动那些STAP

  • 在twitter上注册应用程序并获取客户密钥和客户密钥
  • 参见twitter中的授权文档——参见OAuth简介一节
  • 请求令牌的请求
  • 用户授权请求
  • 访问令牌请求
  • 使用此库的我的代码示例

    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);
    }
    
    受保护的无效页面加载(对象发送方,事件参数e)
    {
    realm=Request.Url.Scheme+“:/”+Request.Url.DnsSafeHost+Request.ApplicationPath;
    如果(!IsPostBack)
    {
    if(Request.QueryString[“oauth_令牌”]==null)
    {
    MakeRequestForToken();
    }
    其他的
    {
    HandleAuthorizeTokenResponse();
    }
    }
    }
    私有void MakeRequestForToken()
    {
    字符串consumerKey=null;
    字符串consumerSecret=null;
    字符串requestTokenEndpoint=null;
    字符串requestTokenCallback=null;
    字符串URL=null;
    consumerKey=“我的客户密钥”;
    ConsumerCret=“我的客户密钥”;
    //推特
    requestTokenEndpoint=”https://api.twitter.com/oauth/request_token";
    requestTokenCallback=GetRouteableUrlFromRelativeUrl(“oAuthGoolgecsSharp/GoogleOauthTry.aspx”);
    //推特
    授权令牌URL=”https://api.twitter.com/oauth/authorize";
    if(String.IsNullOrEmpty(consumerKey)| String.IsNullOrEmpty(ConsumerCret))
    抛出新ArgumentException(“请为所选提供商”、“consumerKey”或“ConsumerCret”设置您的使用者密钥和使用者机密”);
    //步骤1:调用以请求令牌
    var oAuthConsumer=新的oAuthConsumer();
    var requestToken=oAuthConsumer.GetOAuthRequestToken(requestTokenEndpoint、realm、consumerKey、ConsumerCret、requestTokenCallback);
    PersistRequestToken(requestToken);
    //第2步:调用以授权请求令牌
    Response.Redirect(authorizeTokenUrl+“?oauth_token=“+requestToken.token”);
    }
    /// 
    ///步骤3:将请求令牌交换为访问令牌
    /// 
    私人无效授权书
    {
    字符串consumerKey=null;
    字符串consumerSecret=null;
    字符串accessTokenEndpoint=null;
    字符串标记=null;
    字符串验证程序=null;
    provider=“谷歌”;
    token=Request.QueryString[“oauth_token”];
    verifier=Request.QueryString[“oauth_verifier”];
    //谷歌
    //accessTokenEndpoint=”https://www.google.com/accounts/OAuthGetAccessToken";
    //推特
    accessTokenEndpoint=”https://api.twitter.com/oauth/access_token";
    if(String.IsNullOrEmpty(consumerKey)| String.IsNullOrEmpty(ConsumerCret))
    抛出新ArgumentException(“请为所选提供商”、“consumerKey”或“ConsumerCret”设置您的使用者密钥和使用者机密”);
    //将请求令牌交换为访问令牌
    var oAuthConsumer=新的oAuthConsumer();
    var accessToken=oAuthConsumer.GetOAuthAccessToken(accessTokenEndpoint、realm、consumerKey、ConsumerCret、token、verifier、GetRequesttoken().TokenSecret);
    这个.SaveAccessTokken(accessToken);
    Response.Redirect(“~/TaksList.aspx”);
    }
    RequestToken GetRequesttoken()
    {
    var requestToken=(requestToken)会话[“requestToken”];
    删除(“请求令牌”);
    返回请求令牌;
    }
    无效PersistRequestToken(RequestToken RequestToken)
    {
    会话[“RequestToken”]=RequestToken;
    }
    字符串GetRouteableUrlFromRelativeUrl(字符串relativeUrl)
    {
    var url=HttpContext.Current.Request.url;
    返回url.Scheme+“:/”+url.Authority+virtualPath.ToAbsolute(“/”+relativeUrl);
    }
    私有void SaveAccessTokken(AccessToken tokken)
    {
    添加(“AccessTokken”,tokken);
    }
    
  • 发出web请求-例如
  • 使用OauthBase.cs生成签名
  • 使用OAuthUtils.cs和方法调用GetUserInfoAuthorizationHeader生成授权标头
  • 将授权放在请求头中
  • 发送请求并获取数据
  • 参见我的代码示例 私有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;
        }
    
    
    
    
    
    }
    
    受保护的无效页面加载(对象发送方,事件参数e)
    {
    _accessToken=(accessToken)会话[“accessToken”];
    字符串_customerkey=“我的客户密钥”;
    字符串_customerSecret=“我的客户密钥”;
    字符串nostring=“”;
    字符串nnString=“”;
    OAuthBase oauth=新的OAuthBase();
    //推特
    Uri t=新的Uri(“http://api.twitter.com/1/statuses/home_timeline.xml");
    字符串u=oauth.GenerateSignature(t,_customerkey,_customerSecret,_accessToken.Token,
    _accessToken.TokenSecret,“GET”,oauth.GenerateTimeStamp(),
    oauth.generateOnce(),out nostring,out nnString);
    HttpWebRequest请求=(HttpWebRequest)HttpWebRequest.Create(nostring);
    request.Method=“GET”;
    string realm=Request.Url.Scheme+“:/”+Request.Url.DnsSafeHost+Request.ApplicationPath;
    OAuthUtils util=新的OAuthUtils();
    AuthorizeHeader h=util.GetUserInfoAuthorizationHeader(t.ToString(),realm,_customerkey,_customerSecret,
    _accessToken.Token,\u accessToken.TokenSecret,
    
    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;
        }
    
    
    
    
    
    }