在 android 中使用路标请求访问令牌时收到 401

发布于 2024-10-26 21:59:41 字数 3112 浏览 10 评论 0原文

这是我的代码,我不断收到异常“授权失败(服务器回复 401)。如果消费者密钥不正确或签名不匹配,则可能会发生这种情况。”在这一行“provider.retrieveAccessToken(consumer, verifier);”。我已经三次检查了我的消费者密钥和秘密,我的 Twitter 应用程序被设置为浏览器并尝试设置provider.setOAuth10a(true),我已经为此苦苦挣扎了 2 天!我正在使用路标 1.2.1.1(核心和commonshttp4),如果有人可以提供帮助!请我绝望

    private static final String CONSUMER_KEY = "MY_CONSUMER_KEY";
    private static final String CONSUMER_SECRET = "MY_CONSUMER_SECRET";

    private static final String CALLBACK_URL = "tweet-mapper://mainactivity";

    private static final String REQUEST_URL = "https://api.twitter.com/oauth/request_token";
    private static final String ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token";
    private static final String AUTH_URL = "https://api.twitter.com/oauth/authorize";

    private static final String PREFERENCE_FILE = "twitter_oauth.prefs";

    private static CommonsHttpOAuthConsumer consumer;
    private static CommonsHttpOAuthProvider provider;

    private static String ACCESS_KEY;
    private static String ACCESS_SECRET;

    private Twitter twitter;


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        loginViaOAuth();

    }

    private void loginViaOAuth() {
        try {
            consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
            provider.setOAuth10a(true);
            provider = new CommonsHttpOAuthProvider(REQUEST_URL, ACCESS_TOKEN_URL, AUTH_URL);
            String authURL = provider.retrieveRequestToken(consumer, CALLBACK_URL);
            this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authURL)));
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onResume() {

        super.onResume();

        Uri uri = this.getIntent().getData();
        if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
            String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
            Log.d("verifier:", verifier);
            try {

                provider.setOAuth10a(true);
                provider.retrieveAccessToken(consumer, verifier);
                ACCESS_KEY = consumer.getToken();
                ACCESS_SECRET = consumer.getTokenSecret();

                AccessToken a = new AccessToken(ACCESS_KEY, ACCESS_SECRET);

                // initialize Twitter4J
                twitter = new Twitter();
                twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
                twitter.setOAuthAccessToken(a);
                String tweet = "#OAuth working via android app!";

                twitter.updateStatus(tweet);
                Toast.makeText(this, tweet, Toast.LENGTH_LONG).show();

            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

Here is my code, i keep getting an exception "Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match." on this line 'provider.retrieveAccessToken(consumer, verifier);'. I have triple checked my consumer key and secret and my twitter application is set as a Browser and tried setting provider.setOAuth10a(true), i have been struggling on this for 2 days!! I am using signpost 1.2.1.1 (core & commonshttp4), If anyone can help! Please im desperate

    private static final String CONSUMER_KEY = "MY_CONSUMER_KEY";
    private static final String CONSUMER_SECRET = "MY_CONSUMER_SECRET";

    private static final String CALLBACK_URL = "tweet-mapper://mainactivity";

    private static final String REQUEST_URL = "https://api.twitter.com/oauth/request_token";
    private static final String ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token";
    private static final String AUTH_URL = "https://api.twitter.com/oauth/authorize";

    private static final String PREFERENCE_FILE = "twitter_oauth.prefs";

    private static CommonsHttpOAuthConsumer consumer;
    private static CommonsHttpOAuthProvider provider;

    private static String ACCESS_KEY;
    private static String ACCESS_SECRET;

    private Twitter twitter;


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        loginViaOAuth();

    }

    private void loginViaOAuth() {
        try {
            consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
            provider.setOAuth10a(true);
            provider = new CommonsHttpOAuthProvider(REQUEST_URL, ACCESS_TOKEN_URL, AUTH_URL);
            String authURL = provider.retrieveRequestToken(consumer, CALLBACK_URL);
            this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authURL)));
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onResume() {

        super.onResume();

        Uri uri = this.getIntent().getData();
        if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
            String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
            Log.d("verifier:", verifier);
            try {

                provider.setOAuth10a(true);
                provider.retrieveAccessToken(consumer, verifier);
                ACCESS_KEY = consumer.getToken();
                ACCESS_SECRET = consumer.getTokenSecret();

                AccessToken a = new AccessToken(ACCESS_KEY, ACCESS_SECRET);

                // initialize Twitter4J
                twitter = new Twitter();
                twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
                twitter.setOAuthAccessToken(a);
                String tweet = "#OAuth working via android app!";

                twitter.updateStatus(tweet);
                Toast.makeText(this, tweet, Toast.LENGTH_LONG).show();

            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

七月上 2024-11-02 21:59:41

刚刚找到了一个可能的解决方案:您需要在 Twitter 应用程序帐户上设置回调 URL。

Just found out a possible solution: You need to set a Callback URL on your twitter application account.

书间行客 2024-11-02 21:59:41

我在我的 Android 应用程序上遇到了完全相同的问题。更令人沮丧的是,我的推特登录工作正常,但由于某些随机原因开始签名失败。

我进行了很多测试,发现问题来自 OAuth 过程中使用的 Android 浏览器:

  • 如果您使用存储的登录名/密码登录,或者如果您的 Twitter 会话有一个 cookie 并且只是点击“接受”,会提示401错误,
  • 如果手动删除并重新输入密码,就可以了!

我仍然无法理解这如何影响 API 调用,但我猜当您提交带有预先输入信息的“接受”表单时,浏览器中会出现一些混淆。

我很好奇我的解决方法是否也能解决您的问题。我知道这不是一个正确的解决方案,但这是一个开始。

编辑:使用 http:// 而不是 https:// 作为 Twitter OAuth URL,它解决了问题。我仍然不明白发生了什么......

I had exactly the same problem on my Android application. It was even more frustrating that my twitter login was perfectly working and starting to fail on the signature for some random reasons.

I ran a lot of tests and I found that the problem came from the Android browser which is used in the OAuth process:

  • if you are logging in using the stored login/password, or if you have a cookie with your Twitter session and just have to click on "Accept", it fill fail with the 401 error
  • if you manually delete and re-enter your password, then it works!

I still can't understand how this affects the API call, but I guess there is some mix up in the browser when you submit the "accept" form with pre-entered information.

I'd be very curious to see if my workaround solves also your problem. I understand this is not a proper solution, but this is a beginning.

EDIT: use http:// instead of https:// for the Twitter OAuth URLs and it solves the problem. I still don't unsertand what is happening...

乖不如嘢 2024-11-02 21:59:41

检查您的 api 请求,它必须是 .json 或 .xml,例如
https://api.jabbakam.com/network/get_list.json
http://api.twitter.com/1/account/verify_credentials.xml

我建议您使用 Scribe 库,其中有一个用于使用 Twitter API 的内置类。

https://github .com/fernandezpablo85/scribe-java/blob/master/src/test/java/org/scribe/examples/TwitterExample.java

当您创建 Twitter 密钥时,您是否设置了访问级别:读和写?

Check your api request it must be .json or .xml, something like
https://api.jabbakam.com/network/get_list.json or
http://api.twitter.com/1/account/verify_credentials.xml

I advise you to use Scribe library there is a built in class for using Twitter API.

https://github.com/fernandezpablo85/scribe-java/blob/master/src/test/java/org/scribe/examples/TwitterExample.java

When you create your twitter keys did you make Access level: Read and write?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文