在android中使用路标请求访问令牌时获取401
作者:互联网
这是我的代码,我不断收到异常“授权失败(服务器回复401).如果消费者密钥不正确或签名不匹配,就会发生这种情况.”在这一行’provider.retrieveAccessToken(消费者,验证者);’.我已经检查了我的消费者密钥和秘密,并且我的Twitter应用程序被设置为浏览器并尝试设置provider.setOAuth10a(true),我一直在为此奋斗2天!我正在使用路标1.2.1.1(core& 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();
}
}
解决方法:
刚刚找到了一个可能的解决方案:您需要在Twitter应用程序帐户上设置回拨URL.
标签:android,oauth,twitter-oauth,signpost 来源: https://codeday.me/bug/20190710/1420205.html