简体   繁体   English

Twitter,OAuth,Hammock,TweetSharp和Windows Phone 7

[英]Twitter, OAuth, Hammock, TweetSharp and Windows Phone 7

I've been trying for days to get OAuth working with Twitter in my Windows Phone app, but all the information I find is out dated or difficult to follow. 我一直在努力让OAuth在我的Windows Phone应用程序中使用Twitter,但我找到的所有信息都已过时或难以理解。 I eventually got somewhere when I found this blog post http://samjarawan.blogspot.co.uk/2010/09/building-real-windows-phone-7-twitter_18.html which got me all the way to getting the access token, at which point it failed. 当我发现这篇博客http://samjarawan.blogspot.co.uk/2010/09/building-real-windows-phone-7-twitter_18.html时,我最终得到了某个地方,这让我获得了访问令牌它失败了。

My code is almost identical to the one in the blog post, pretty much just changed the consumer key and consumer secret. 我的代码几乎与博客文章中的代码相同,几乎只是改变了消费者密钥和消费者秘密。 Even their app doesn't work. 即使他们的应用程序也无效。 It displays the Twitter login screen fine, and successfully authenticates, but in the RequestAccessToken function, it fails at this point: 它显示Twitter登录屏幕正常,并成功进行身份验证,但在RequestAccessToken函数中,它在此时失败:

if (String.IsNullOrEmpty(twitteruser.AccessToken) || String.IsNullOrEmpty(twitteruser.AccessTokenSecret))
{
    Dispatcher.BeginInvoke(() => MessageBox.Show(response.Content));
    return;
}

The really annoying thing is the message box only shows the Unicode replacement character ( ) and nothing else. 真正烦人的事情是消息框只显示Unicode替换字符( )而没有别的。 I also checked the response.StatusCode and it is OK, so there is no error as far as I can tell. 我还检查了response.StatusCode,它没关系,所以我可以告诉你没有错误。

If someone could help me out with this, that would be great. 如果有人可以帮我解决这个问题,那就太好了。 I've seen other tutorials which require the user type in a PIN, but I haven't been able to get any of those to work either. 我已经看过其他需要用户输入PIN的教程,但是我也无法使用其中任何一个。

EDIT: I've just tried getting TweetSharp to work, but once again it fails to get the access token. 编辑:我刚刚尝试让TweetSharp工作,但再次无法获得访问令牌。 Here is the code I'm using for TweetSharp: 这是我用于TweetSharp的代码:

public partial class TwitterAuthorisationPage : PhoneApplicationPage
{
    private const string consumerKey = "myKey";
    private const string consumerSecret = "mySecret"; // These are the correct values for my app
    private const string requestTokenUri = "https://api.twitter.com/oauth/request_token";
    private const string oAuthVersion = "1.0a";
    private const string authorizeUri = "https://api.twitter.com/oauth/authorize";
    private const string accessTokenUri = "https://api.twitter.com/oauth/access_token";
    private const string callbackUri = "http://bing.com";

    private TwitterService twitterService = new TwitterService(consumerKey, consumerSecret);
    private OAuthRequestToken _requestToken = null;

    public TwitterAuthorisationPage()
    {
        InitializeComponent();
    }

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        twitterService.GetRequestToken((requestToken, response) =>
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                _requestToken = requestToken;
                Dispatcher.BeginInvoke(() => BrowserControl.Navigate(twitterService.GetAuthorizationUri(requestToken)));
            }
            else
            {
                Dispatcher.BeginInvoke(() => MessageBox.Show("Failed to connect to Twitter. Please try again.\n" + response.StatusDescription));
            }
        });
    }

    private void ConfirmButton_Click(object sender, RoutedEventArgs e)
    {
        twitterService.GetAccessToken(_requestToken, PINEntry.Text, (accessToken, response) =>
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                //These lines just print ?
                System.Diagnostics.Debug.WriteLine(accessToken.Token);
                System.Diagnostics.Debug.WriteLine(accessToken.TokenSecret);
                twitterService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
                twitterService.VerifyCredentials((user, verifyResponse) =>
                {
                    if (verifyResponse.StatusCode == HttpStatusCode.OK)
                    {
                        Dispatcher.BeginInvoke(() => MessageBox.Show(user.Name));
                    }
                    else
                    {
                        // Fails here
                        Dispatcher.BeginInvoke(() => MessageBox.Show("Failed to connect to Twitter. Please try again.1\n" + verifyResponse.StatusDescription));
                    }
                });
            }
            else
            {
                Dispatcher.BeginInvoke(() => MessageBox.Show("Failed to connect to Twitter. Please try again.0\n" + response.StatusDescription));
            }
        });
    }
}

EDIT 2: Could it be to do with this? 编辑2:这可能与此有关吗? https://dev.twitter.com/blog/ssl-upgrade-for-twitterapi https://dev.twitter.com/blog/ssl-upgrade-for-twitterapi

I worked it out! 我解决了! It turns out Twitter was returning the access token Gzipped. 事实证明Twitter正在返回访问令牌Gzipped。 Using the method described in the blog post, I had to change the second RestClient to be constructed like so: 使用博客文章中描述的方法,我不得不改变第二个RestClient,如下所示:

var client = new RestClient
{
    Authority = "https://api.twitter.com/oauth",
    Credentials = credentials,
    HasElevatedPermissions = true,
    SilverlightAcceptEncodingHeader = "gzip",
    DecompressionMethods = DecompressionMethods.GZip
};

And now it works! 现在它有效!

I am having the same problem but I didn't understand your solution, could you explain a bit more where you changed the rest client? 我遇到了同样的问题,但我不明白你的解决方案,你能解释一下你改变其他客户端的地方吗?

-----EDIT---- - - -编辑 - -

I finally was able to make it work with TweetSharp. 我终于能够使用TweetSharp了。 I downloaded the source code and added the lines you mentioned to the rest client configuration it uses and the compiled the project again. 我下载了源代码,并将您提到的行添加到它使用的其余客户端配置中,并再次编译项目。 Since i cannot push my changes to that github, I upload the dll here. 由于我无法将更改推送到该github,因此我在此处上传了dll。 TweetSharp recompiled dll TweetSharp重新编译了DLL

This is the code I use which with it works 这是我使用的代码,它与它一起工作

// Step 1 - Retrieve an OAuth Request Token
        Service.GetRequestToken((requestToken, response) =>
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Request = requestToken;
                Uri uri = Service.GetAuthorizationUri(requestToken);
                Dispatcher.BeginInvoke(() =>
                {
                    Browser.Navigate(uri);
                }
               );
            }
        });


//Step 2, get the pincode

string html = Browser.SaveToString(); //gets the DOM as a string
            Regex expression = new Regex(@"<code>(?<word>\w+)</code>"); 
            Match match = expression.Match(html);
            string pin = match.Groups["word"].Value;
            if (pin != "")
            {                    
                loginTwitter(pin); //we login with the pin extracted
            }

//step 3, get access tokens from twitter
 private void loginTwitter(string pin)
    {
        Service.GetAccessToken(Request, pin, processAccessToken);
    }


    public void processAccessToken(OAuthAccessToken access, TwitterResponse Response){
        if (Response.StatusCode == HttpStatusCode.OK)
        {
            if (access != null)
            {
                Access = access; // Store it for reuse
                Service.AuthenticateWith(access.Token, access.TokenSecret);
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM