问题
Iam not able to share the content with the twitter.whenever I press the login to twitter button in my application it goes to the webview where it authorizes my app and then comes back to the login page i.e(it doesnt shares).I have given my code below...kindly help..
Constants.java
package com.Background_fb_twitter;
public class Constants {
public static final String CONSUMER_KEY = "UBn5Lh4vUdxc1JqKCOujyw";
public static final String CONSUMER_SECRET= "elbHrX80tfsUsUFjvmjC4RUc4152uk4jR6MATQrxI";
public static final String REQUEST_URL = "https://api.twitter.com/oauth/request_token";
public static final String ACCESS_URL = "https://api.twitter.com/oauth/access_token";
public static final String AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize";
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-twitter";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
}
OAuthRequestTokenTask.java
package com.Background_fb_twitter;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import android.content.Context;
import android.content.Intent;
import twitter4j.Twitter;
import twitter4j.http.AccessToken;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
/**
* An asynchronous task that communicates with Twitter to
* retrieve a request token.
* (OAuthGetRequestToken)
*
* After receiving the request token from Twitter,
* pop a browser to the user to authorize the Request Token.
* (OAuthAuthorizeToken)
*
*/
public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {
final String TAG = getClass().getName();
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
/**
*
* We pass the OAuth consumer and provider.
*
* @param context
* Required to be able to start the intent to launch the browser.
* @param provider
* The OAuthProvider object
* @param consumer
* The OAuthConsumer object
*/
public OAuthRequestTokenTask(Context context,OAuthConsumer consumer,OAuthProvider provider) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
}
/**
*
* Retrieve the OAuth Request Token and present a browser to the user to authorize the token.
*
*/
@Override
protected Void doInBackground(Void... params) {
try {
Log.i(TAG, "Retrieving request token from Google servers");
final String url = provider.retrieveRequestToken(consumer, Constants.OAUTH_CALLBACK_URL);
Log.i(TAG, "Popping a browser with the authorize URL : " + url);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
context.startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "Error during OAUth retrieve request token", e);
}
return null;
}
}
PrepareRequestTokenActivity.java
package com.Background_fb_twitter;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import android.app.Activity;
import twitter4j.Twitter;
import twitter4j.http.AccessToken;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
/**
* Prepares a OAuthConsumer and OAuthProvider
*
* OAuthConsumer is configured with the consumer key & consumer secret.
* OAuthProvider is configured with the 3 OAuth endpoints.
*
* Execute the OAuthRequestTokenTask to retrieve the request, and authorize the
* request.
*
* After the request is authorized, a callback is made here.
*
*/
public class PrepareRequestTokenActivity extends Activity {
final String TAG = getClass().getName();
private OAuthConsumer consumer;
private OAuthProvider provider;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
this.consumer = new CommonsHttpOAuthConsumer(
Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
this.provider = new CommonsHttpOAuthProvider(Constants.REQUEST_URL,
Constants.ACCESS_URL, Constants.AUTHORIZE_URL);
} catch (Exception e) {
Log.e(TAG, "Error creating consumer / provider", e);
}
Log.i(TAG, "Starting task to retrieve request token.");
new OAuthRequestTokenTask(this, consumer, provider).execute();
}
/**
* Called when the OAuthRequestTokenTask finishes (user has authorized the
* request token). The callback URL will be intercepted here.
*/
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
final Uri uri = intent.getData();
if (uri != null
&& uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
Log.i(TAG, "Callback received : " + uri);
Log.i(TAG, "Retrieving Access Token");
new RetrieveAccessTokenTask(this, consumer, provider, prefs)
.execute(uri);
finish();
}
}
public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
private SharedPreferences prefs;
public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,
OAuthProvider provider, SharedPreferences prefs) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
this.prefs = prefs;
}
/**
* Retrieve the oauth_verifier, and store the oauth and
* oauth_token_secret for future API calls.
*/
@Override
protected Void doInBackground(Uri... params) {
final Uri uri = params[0];
final String oauth_verifier = uri
.getQueryParameter(OAuth.OAUTH_VERIFIER);
try {
provider.retrieveAccessToken(consumer, oauth_verifier);
final Editor edit = prefs.edit();
edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
edit.putString(OAuth.OAUTH_TOKEN_SECRET,
consumer.getTokenSecret());
edit.commit();
String token = prefs.getString(OAuth.OAUTH_TOKEN,
"1685102257-UObwXDCu5YvUNsmNchiTFRSMdHNQISdfXW0hN9Z");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET,
"owKPgAVxlju9QcaGLZSCcponXqlGTQOxWnwWl22Avts");
consumer.setTokenWithSecret(token, secret);
context.startActivity(new Intent(context,
Background_fb_twitterActivity.class));
executeAfterAccessTokenRetrieval();
Log.i(TAG, "OAuth - Access Token Retrieved");
} catch (Exception e) {
Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
}
return null;
}
private void executeAfterAccessTokenRetrieval() {
String msg = getIntent().getExtras().getString("tweet_msg");
try {
TwitterUtils.sendTweet(prefs, msg);
} catch (Exception e) {
Log.e(TAG, "OAuth - Error sending to Twitter", e);
}
}
}
}
share_text.java
package com.Background_fb_twitter;
import com.facebook.android.Facebook;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class share_text extends Activity {
private EditText edit;
private Button btns;
/** face book details */
static final String APP_ID = "158224494375077";
static final String[] PERMISSIONS = new String[] { "publish_stream" };
static final String TOKEN = "access_token";
static final String EXPIRES = "expires_in";
static final String KEY = "facebook-credentials";
static Facebook facebook1;
private boolean FB_LOGIN = false;
/** ---------------------------------- */
private SharedPreferences prefs1;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.share_alert);
this.prefs1 = PreferenceManager.getDefaultSharedPreferences(this);
edit = (EditText) findViewById(R.id.editText1);
btns = (Button) findViewById(R.id.button1);
btns.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String str = edit.getText().toString();
if (str != "") {
postToWall(str, share_text.this);
if (TwitterUtils.isAuthenticated(prefs1)) {
sendTweet(share_text.this, str);
}
} else {
edit.setError("Please Enter Text!");
}
}
});
}
public static void postToWall(String message, Context con) {
facebook1 = new Facebook(APP_ID);
String st = get_token__(con);
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
if (st.length() > 0) {
parameters.putString("access_token", "" + st);
}
try {
facebook1.request("me");
String response = facebook1.request("me/feed", parameters, "POST");
Log.d("Tests--->*************", "got response: " + response);
if (response == null
|| response.equals("")
|| response.equals("false")
|| response
.equalsIgnoreCase("{\"error\":{\"message\":\"An active access token must be used to query information about the current user.\",\"type\":\"OAuthException\",\"code\":2500}}")) {
showToast("Blank response. please loginf again in facebook",
con);
clear_fb_data(con);
} else {
showToast("Message posted to your facebook wall!", con);
}
} catch (Exception e) {
showToast("Failed to post to wall!", con);
e.printStackTrace();
}
}
private static String get_token__(Context con) {
// TODO Auto-generated method stub
SharedPreferences sharedPreferences = con.getSharedPreferences(KEY,
Context.MODE_PRIVATE);
return sharedPreferences.getString(TOKEN, null);
}
private static void clear_fb_data(Context con) {
// TODO Auto-generated method stub
SharedPreferences se = PreferenceManager
.getDefaultSharedPreferences(con);
Editor editor = se.edit();
editor.remove(TOKEN);
editor.remove(EXPIRES);
editor.commit();
}
private static void showToast(String message, Context con) {
Toast.makeText(con, message, Toast.LENGTH_SHORT).show();
}
/** twitter methods-------------------------- start */
private final static Handler mTwitterHandler = new Handler();
private static SharedPreferences prefs;
public static boolean TWEET_LOGIN = false;
final static Runnable mUpdateTwitterNotification = new Runnable() {
public void run() {
}
};
public static void sendTweet(Context con, final String msj) {
prefs = PreferenceManager.getDefaultSharedPreferences(con);
Thread t = new Thread() {
public void run() {
try {
TwitterUtils.sendTweet(prefs, msj);
mTwitterHandler.post(mUpdateTwitterNotification);
} catch (Exception ex) {
ex.printStackTrace();
Log.d("kiran-->send tweet:", ex.getMessage().toString());
}
}
};
t.start();
}
/** twitter methods-------------------------- end */
}
TwitterUtils.java
package com.Background_fb_twitter;
import oauth.signpost.OAuth;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import android.content.SharedPreferences;
import android.net.wifi.WifiConfiguration.Status;
import android.util.Log;
public class TwitterUtils {
public static boolean isAuthenticated(SharedPreferences prefs) {
String token = prefs.getString(OAuth.OAUTH_TOKEN, "1685102257-UObwXDCu5YvUNsmNchiTFRSMdHNQISdfXW0hN9Z");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "owKPgAVxlju9QcaGLZSCcponXqlGTQOxWnwWl22Avts");
AccessToken a = new AccessToken(token, secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY,
Constants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
try {
twitter.getAccountSettings();
return true;
} catch (TwitterException e) {
return false;
}
}
public static void sendTweet(SharedPreferences prefs, String msg)
throws Exception {
String token = prefs.getString(OAuth.OAUTH_TOKEN, "1685102257-UObwXDCu5YvUNsmNchiTFRSMdHNQISdfXW0hN9Z");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "owKPgAVxlju9QcaGLZSCcponXqlGTQOxWnwWl22Avts");
Log.d("kiran-> token", token);
Log.d("kiran-> secret", secret);
Log.d("kiran-> msg", msg);
try {
AccessToken a = new AccessToken(token, secret);
Log.d("acc_token :", "" + a);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY,
Constants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
twitter.updateStatus(""+msg);
} catch (Exception e) { // TODO: handleexception
Log.d("error dj-->", e.getMessage().toString());
}
// try {
// TwitterFactory factory = new TwitterFactory();
// Twitter twitter = factory.getInstance();
// //AccessToken accestoken = new AccessToken(token, secret);
// AccessToken accestoken = new AccessToken("hx6GH2dEk0APOeMKCBof1g", "UTufsnbngxKojsbEEfwLbCoqoSjSk3SeVEMge9YZk0");
//
// twitter.setOAuthAccessToken(accestoken);
// Status status = (Status) twitter.updateStatus(msg);
// System.out.println("it worked!");
// if (((twitter4j.Status) status).getId() == 0) {
// System.out
// .println("Error occured while posting tweets to twitter");
// }
//
// } catch (Exception e) {
// e.printStackTrace();
// Log.d("error dj-->", e.getMessage().toString());
// }
}
}
logcat error output
08-27 12:52:18.522: I/com.Background_fb_twitter.OAuthRequestTokenTask(1433): Popping a browser with the authorize URL : https://api.twitter.com/oauth/authorize?oauth_token=PwL8lrboJD3RIlvc0abFjbEbJSokql1uyCnweyyKJI
08-27 12:53:19.532: I/com.Background_fb_twitter.PrepareRequestTokenActivity(1433): Callback received : x-oauthflow-twitter://callback?oauth_token=PwL8lrboJD3RIlvc0abFjbEbJSokql1uyCnweyyKJI&oauth_verifier=XouInhrvXs8shiqW9iNYZOwUPD3Bfm9y9xbScLWik
08-27 12:53:19.532: I/com.Background_fb_twitter.PrepareRequestTokenActivity(1433): Retrieving Access Token
08-27 12:53:34.872: I/global(1433): Loaded time zone names for en_US in 3472ms.
08-27 12:53:38.492: I/global(1433): Loaded time zone names for en_US in 3595ms.
08-27 12:53:38.502: W/ResponseProcessCookies(1433): Invalid cookie header: "set-cookie: guest_id=v1%3A137758820381898039; Domain=.twitter.com; Path=/; Expires=Thu, 27-Aug-2015 07:23:24 UTC". Unable to parse expires attribute: Thu, 27-Aug-2015 07:23:24 UTC
08-27 12:53:38.632: D/kiran-> token(1433): 1685102257-UObwXDCu5YvUNsmNchiTFRSMdHNQISdfXW0hN9Z
08-27 12:53:38.693: D/kiran-> secret(1433): owKPgAVxlju9QcaGLZSCcponXqlGTQOxWnwWl22Avts
08-27 12:53:38.803: D/acc_token :(1433): AccessToken{screenName='null', userId=0}
08-27 12:53:39.682: D/error dj-->(1433): 403:The request is understood, but it has been refused. An accompanying error message will explain why. This code is used when requests are being denied due to update limits (http://support.twitter.com/forums/10711/entries/15364).
08-27 12:53:39.682: D/error dj-->(1433): <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
08-27 12:53:39.682: D/error dj-->(1433): <HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
08-27 12:53:39.682: D/error dj-->(1433): <TITLE>ERROR: The requested URL could not be retrieved</TITLE>
08-27 12:53:39.682: D/error dj-->(1433): <STYLE type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></STYLE>
08-27 12:53:39.682: D/error dj-->(1433): </HEAD><BODY>
08-27 12:53:39.682: D/error dj-->(1433): <H1>ERROR</H1>
08-27 12:53:39.682: D/error dj-->(1433): <H2>The requested URL could not be retrieved</H2>
08-27 12:53:39.682: D/error dj-->(1433): <HR noshade size="1px">
08-27 12:53:39.682: D/error dj-->(1433): <P>
08-27 12:53:39.682: D/error dj-->(1433): While trying to retrieve the URL:
08-27 12:53:39.682: D/error dj-->(1433): <A HREF="http://api.twitter.com/1/statuses/update.json">http://api.twitter.com/1/statuses/update.json</A>
08-27 12:53:39.682: D/error dj-->(1433): <P>
08-27 12:53:39.682: D/error dj-->(1433): The following error was encountered:
08-27 12:53:39.682: D/error dj-->(1433): <STRONG>
08-27 12:53:39.682: D/error dj-->(1433): Access Denied.
08-27 12:53:39.682: D/error dj-->(1433): </STRONG>
08-27 12:53:39.682: D/error dj-->(1433): <ADDRESS>
08-27 12:53:39.682: D/error dj-->(1433): Generated Tue, 27 Aug 2013 07:23:40 GMT by localhost (squid/2.7.STABLE9)
08-27 12:53:39.682: D/error dj-->(1433): </ADDRESS>
08-27 12:53:39.682: D/error dj-->(1433): </BODY></HTML>
08-27 12:53:39.682: I/com.Background_fb_twitter.PrepareRequestTokenActivity(1433): OAuth - Access Token Retrieved
来源:https://stackoverflow.com/questions/18459201/why-am-i-not-able-to-share-the-content-with-twitter