无法使用 twitter4j 发推文
当我尝试从 Android 应用程序发送推文(固定消息)时,我遇到了问题。我已经尝试过使用来自不同论坛的 4 个不同的代码示例(全部使用 twitter4j),但总是得到相同的结果:我输入了我的用户名和密码,身份验证工作正常,但之后我总是被重定向到“callback_url”中指定的 URL(我已经使用现有 URL 进行了测试,但也不存在),并且该推文未发布。 正如您所看到的,我将身份验证和发送推文的方法分开,但是一旦身份验证完成,控制权就永远不会返回到我的应用程序。我正在使用 android 2.1(也用 2.2 进行了测试)。 任何帮助将非常感激。 提前致谢。
public void onCreate(Bundle savedInstanceState) {
mTwitter = new TwitterFactory().getInstance();
mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
if (mPrefs.contains(PREF_ACCESS_TOKEN)) {
loginAuthorisedUser();
} else {
loginNewUser();
}
}
private void loginNewUser() {
try {
mReqToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);
WebView twitterSite = new WebView(this);
twitterSite.loadUrl(mReqToken.getAuthenticationURL());
setContentView(twitterSite);
} catch (TwitterException e) {
Toast.makeText(this, "Twitter Login error, try again later", Toast.LENGTH_SHORT).show();
}
}
private void loginAuthorisedUser() {
String token = mPrefs.getString(PREF_ACCESS_TOKEN, null);
String secret = mPrefs.getString(PREF_ACCESS_TOKEN_SECRET, null);
// Create the twitter access token from the credentials we got previously
AccessToken at = new AccessToken(token, secret);
mTwitter.setOAuthAccessToken(at);
Toast.makeText(this, "Welcome back", Toast.LENGTH_SHORT).show();
buttonTweet(null);
}
/**
* Catch when Twitter redirects back to our {@link CALLBACK_URL}</br>
* We use onNewIntent as in our manifest we have singleInstance="true" if we did not the
* getOAuthAccessToken() call would fail
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
dealWithTwitterResponse(intent);
}
/**
* Twitter has sent us back into our app</br>
* Within the intent it set back we have a 'key' we can use to authenticate the user
*
* @param intent
*/
private void dealWithTwitterResponse(Intent intent) {
Uri uri = intent.getData();
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) { // If the user has just logged in
String oauthVerifier = uri.getQueryParameter("oauth_verifier");
authoriseNewUser(oauthVerifier);
}
}
/**
* Create an access token for this new user</br>
* Fill out the Twitter4j helper</br>
* And save these credentials so we can log the user straight in next time
*
* @param oauthVerifier
*/
private void authoriseNewUser(String oauthVerifier) {
try {
AccessToken at = mTwitter.getOAuthAccessToken(mReqToken, oauthVerifier);
mTwitter.setOAuthAccessToken(at);
saveAccessToken(at);
// Set the content view back after we changed to a webview
// setContentView(R.layout.main);
tweetMessage();
} catch (TwitterException e) {
Toast.makeText(this, "Twitter auth error x01, try again later", Toast.LENGTH_SHORT).show();
}
}
private void tweetMessage() {
try {
mTwitter.updateStatus("Test - Tweeting");
Toast.makeText(this, "Tweet Successful!", Toast.LENGTH_SHORT).show();
} catch (TwitterException e) {
Toast.makeText(this, "Tweet error, try again later", Toast.LENGTH_SHORT).show();
}
}
private void saveAccessToken(AccessToken at) {
String token = at.getToken();
String secret = at.getTokenSecret();
Editor editor = mPrefs.edit();
editor.putString(PREF_ACCESS_TOKEN, token);
editor.putString(PREF_ACCESS_TOKEN_SECRET, secret);
editor.commit();
}
AndroidManifest 中的活动声明:
<activity android:name=".share.twitter.TwitterActivity" android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http://www.someurl.com" />
</intent-filter>
</activity>
I'm facing a problem when a try to send a tweet (fixed message) from my Android app. I've tried it with 4 different code samples (all of them using twitter4j), taken from different forums, but always got the same result: I put my user and password, the authentication works fine, but after that I'm always redirected to the URL specified in "callback_url" (I've tested with existing urls and not existing as well) and the tweet is not published.
As you can see, I have separated methods for authentication and for sending the tweet, but once the authentication is finished, the control is never returned to my app. I'm using android 2.1 (tested with 2.2 too).
Any help will be really appreciated.
Thanks in advance.
public void onCreate(Bundle savedInstanceState) {
mTwitter = new TwitterFactory().getInstance();
mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
if (mPrefs.contains(PREF_ACCESS_TOKEN)) {
loginAuthorisedUser();
} else {
loginNewUser();
}
}
private void loginNewUser() {
try {
mReqToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);
WebView twitterSite = new WebView(this);
twitterSite.loadUrl(mReqToken.getAuthenticationURL());
setContentView(twitterSite);
} catch (TwitterException e) {
Toast.makeText(this, "Twitter Login error, try again later", Toast.LENGTH_SHORT).show();
}
}
private void loginAuthorisedUser() {
String token = mPrefs.getString(PREF_ACCESS_TOKEN, null);
String secret = mPrefs.getString(PREF_ACCESS_TOKEN_SECRET, null);
// Create the twitter access token from the credentials we got previously
AccessToken at = new AccessToken(token, secret);
mTwitter.setOAuthAccessToken(at);
Toast.makeText(this, "Welcome back", Toast.LENGTH_SHORT).show();
buttonTweet(null);
}
/**
* Catch when Twitter redirects back to our {@link CALLBACK_URL}</br>
* We use onNewIntent as in our manifest we have singleInstance="true" if we did not the
* getOAuthAccessToken() call would fail
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
dealWithTwitterResponse(intent);
}
/**
* Twitter has sent us back into our app</br>
* Within the intent it set back we have a 'key' we can use to authenticate the user
*
* @param intent
*/
private void dealWithTwitterResponse(Intent intent) {
Uri uri = intent.getData();
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) { // If the user has just logged in
String oauthVerifier = uri.getQueryParameter("oauth_verifier");
authoriseNewUser(oauthVerifier);
}
}
/**
* Create an access token for this new user</br>
* Fill out the Twitter4j helper</br>
* And save these credentials so we can log the user straight in next time
*
* @param oauthVerifier
*/
private void authoriseNewUser(String oauthVerifier) {
try {
AccessToken at = mTwitter.getOAuthAccessToken(mReqToken, oauthVerifier);
mTwitter.setOAuthAccessToken(at);
saveAccessToken(at);
// Set the content view back after we changed to a webview
// setContentView(R.layout.main);
tweetMessage();
} catch (TwitterException e) {
Toast.makeText(this, "Twitter auth error x01, try again later", Toast.LENGTH_SHORT).show();
}
}
private void tweetMessage() {
try {
mTwitter.updateStatus("Test - Tweeting");
Toast.makeText(this, "Tweet Successful!", Toast.LENGTH_SHORT).show();
} catch (TwitterException e) {
Toast.makeText(this, "Tweet error, try again later", Toast.LENGTH_SHORT).show();
}
}
private void saveAccessToken(AccessToken at) {
String token = at.getToken();
String secret = at.getTokenSecret();
Editor editor = mPrefs.edit();
editor.putString(PREF_ACCESS_TOKEN, token);
editor.putString(PREF_ACCESS_TOKEN_SECRET, secret);
editor.commit();
}
Declaration of activity in AndroidManifest:
<activity android:name=".share.twitter.TwitterActivity" android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http://www.someurl.com" />
</intent-filter>
</activity>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Android 应用程序中的方案和主机应该是该应用程序所独有的,以便 Android 知道哪个应用程序应该处理回调。你现在所拥有的让 android 认为你的应用程序可以使用“http”方案处理网页浏览。 在此处查看该帖子的答案。具体来说,《弗兰肯斯坦》描述了如何设置方案和主机,我的代码将向您展示如何处理 onResume()。
The scheme and host in your android app should be something unique to the app so that android knows what app should handle the callback. What you have now makes android think your app can handle web browsing with the "http" scheme. Check out the answers to the post here. Specifically, frankenstein describes how to setup the scheme and hosts, and my code will show you how to handle the onResume().
这里是一个指向单文件解决方案的链接,该解决方案准确解释了如何将图片/文本推文集成到 Android 应用程序中。
我刚刚处理完这个问题,而不是尝试修复您的代码,而是尝试使用提供的代码。它应该无需修改即可工作,并且可以通过一次调用 tweet() 函数来发送推文。
Here is a link to a one file solution that explains exactly how to integrate picture/text tweets into an android app.
I just got through dealing with this and rather than try to fix your code try using the code supplied. It should work without modification and can send a tweet with one call to a tweet() function.