im trying to post status updates to twitter. I am using the Twitter4j lib. My code runs without crashing but in the log cat is says "401:Authentication credentials
(https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
{"request":"\/1.1\/statuses\/update.json","error":"Read-only application cannot POST."}
any help? I have signed up on twitter and i check the read and write permissions.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Runnable runnable = new Runnable() {
public void run() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey("kkwfh72794883jjg");
builder.setOAuthConsumerSecret("77j3jgweqwewerrud3434567hgfd");
// Access Token
String access_token = "lokiujyhtgrfedvwn325zckjdhdgeAHGsw23";
// Access Token Secret
String access_token_secret = "QsRgfgHJMsjeh5762JHF2dgswrfMNQljsG";
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
try {
twitter4j.Status response = twitter.updateStatus("updated via myapp");
Log.d("Status", "> " + response.getText());
// Error in updating status
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("Twitter Update Error", e.getMessage());
}
}
};
Thread mythread = new Thread(runnable);
mythread.start();
}
I was having similar issue. What I did was:
Check if your app has Read and Write permissions
If it doesn't, check the permissions radiobutton, and click Update Settings
After that, you must manually regenerate your access tokens (I regenerated consumer key, too)
Hope this will help other strugglers.
I think you should change your code:
Like this:
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey("kkwfh72794883jjg");
builder.setOAuthConsumerSecret("77j3jgweqwewerrud3434567hgfd");
OAuthAuthorization auth = new OAuthAuthorization(builder.build());
// Access Token
String access_token = "lokiujyhtgrfedvwn325zckjdhdgeAHGsw23";
// Access Token Secret
String access_token_secret = "QsRgfgHJMsjeh5762JHF2dgswrfMNQljsG";
Twitter twitter = new TwitterFactory().getInstance(auth);
I need to get access token and send it to the server. With that access token server should get all user details, like name, profile picture and email.
I can get access token using Scopes.PLUS_LOGIN and Scopes.PLUS_ME, but with that access token server can't get user email.
Here is my code:
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String token = null;
String scope = "oauth2:" + Scopes.PLUS_LOGIN + " " + Scopes.PLUS_ME;
try {
token = GoogleAuthUtil.getToken(
getApplicationContext(),
Plus.AccountApi.getAccountName(mGoogleApiClient),
scope);
appUser.setToken(token);
} catch (IOException transientEx) {
// Network or server error, try later
Log.e(TAG, transientEx.toString());
} catch (UserRecoverableAuthException e) {
// Recover (with e.getIntent())
} catch (GoogleAuthException authEx) {
// The call is not ever expected to succeed
// assuming you have already verified that
// Google Play services is installed.
Log.e(TAG, authEx.toString());
}
return token;
}
#Override
protected void onPostExecute(String token) {
Log.i(TAG, "Access token retrieved:" + appUser.getToken());
// Get user's information
}
};
}
Does anybody know how to solve this problem?
You are missing the scope
https://www.googleapis.com/auth/userinfo.email
I tested the other scopes and only that one appears to return the users email. You can test the different scopes and what they return here: People: get.
Note: I'm not an android programmer, you will probably have better luck finding out how to request that scope with android. I am looking, but haven't been able to find it.
Looks like the scope might just be email https://developers.google.com/+/api/oauth#email
I have been at this since the weekend and I am at an impasse. I am pretty new to programming and suspect I am in over my head because I have read every link under "Similar Questions" and it either does not apply or confuses me more.
I am using the Twitter4j API and I worked from code sample no. 7 on the twitter4j website on OAuth support at http://twitter4j.org/en/code-examples.html.
As a skill-building project, I want to make an Android celebrity fan app that will download the timeline from the celebrity's public account. The goal is to execute a timeline download of all the tweets. I do not want the user to login to Twitter with this app or post tweets. The app just downloads a timeline in the background and displays the tweets, probably in a list view.
My code is not executing the following line. It seems to just hang there waiting for something to happen.
RequestToken requestToken = twitter.getOAuthRequestToken();
I have internet permissions in manifest. At this point, I am so confused, I do not even know if I have registered my app correctly. I have the four keys (consumer, consumer secret, access, and access secret).
Settings
-Website: made something up
-Application Type: Read Only
-Callback URL: left it blank
-I did not opt in to "Sign In With Twitter."
OAuth Tool
-Request Type: GET
-Request URI: https://api.twitter.com/1/ (probably wrong)
This is my code:
public class TwitterActivity extends Activity
{
Button mButtonTweets;
String JSONString = null;
TextView JSONContent;
class GetTwitterTimeline extends AsyncTask<Void, String, String>
{
#Override
protected String doInBackground(Void... params)
{
try
{
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("")
.setOAuthConsumerSecret("")
.setOAuthAccessToken("")
.setOAuthAccessTokenSecret("");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
try
{
RequestToken requestToken = twitter.getOAuthRequestToken();
AccessToken accessToken = null;
while (accessToken == null)
{
onProgressUpdate(requestToken.getAuthenticationURL());
try
{
accessToken = twitter.getOAuthAccessToken();
}//try
catch(TwitterException te)
{
if (te.getStatusCode() == 401)
{
onProgressUpdate("Unable to get the access token");
}//if
else
{
te.printStackTrace();
}//else
}//catch
}//while
onProgressUpdate("Got Access Token");
onProgressUpdate("Access Token: " + accessToken.getToken());
onProgressUpdate("Access Token Secret: " + accessToken.getTokenSecret());
}//try
catch (IllegalStateException ie)
{
if(!twitter.getAuthorization().isEnabled())
{
onProgressUpdate("OAuth consumer key/secret is not set.");
}//if
}//catch
}//try
catch (TwitterException te)
{
te.printStackTrace();
onProgressUpdate("Failed to get timeline");
}//catch
String JSONString = "JSON content will go here";
return JSONString;
}//doInBackground
protected void onProgressUpdate(String logEntry)
{
Log.d("twitter4j", logEntry);
}
#Override
protected void onPostExecute(String jsonString)
{
JSONString = jsonString;
}
}//end inner class
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_twitter);
new GetTwitterTimeline().execute();
JSONContent = (TextView) findViewById(R.id.textview_tweets);
mButtonTweets = (Button) findViewById(R.id.button_tweets);
mButtonTweets.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
JSONContent.setText(JSONString);
}
});
}
}
Twitter API has been updated. So Request URI: https://api.twitter.com/1/ won't work.
Also AFAIK the way you are trying to make the app won't work out. You need some kind of authentication. I also dumped one of my app after this API change. :(
Read the following link:
https://dev.twitter.com/docs/api/1.1/overview
We have contacted Google about this and we are on chat
The issue seems to be fixed for devices except Samsung phones.
I'm adding a Google+ sign in option to an app per the official instructions. Once the user has selected their account I would like my server to retrieve their Google+ profile info and update their profile on our site to match.
The first part - having the user select a Google account locally - seems to work just fine. When I try to request a token for the selected account, the Google auth dialog displays with the appropriate parameters; however, when I authorize the app using that dialog and re-request the token, GoogleAuthUtil.getToken(...) again throws a UserRecoverableAuthException (NeedPermission, not GooglePlayServicesAvailabilityException) and I get the same dialog asking me to approve!
This behavior is present on a Samsung S3 running Android 4.1.1 (with 3 Google accounts) and an Acer A100 running 4.0.3. It is NOT present on an HTC Glacier running 2.3.4. Instead, the HTC Glacier gives me a valid auth code. All devices have the latest iteration of Google Play Services installed and are using different Google+ accounts.
Anyone seen this before? Where can I start with debugging?
Here's the complete code - is anything obviously awry?
public class MyGooglePlusClient {
private static final String LOG_TAG = "GPlus";
private static final String SCOPES_LOGIN = Scopes.PLUS_LOGIN + " " + Scopes.PLUS_PROFILE;
private static final String ACTIVITIES_LOGIN = "http://schemas.google.com/AddActivity";
private static MyGooglePlusClient myGPlus = null;
private BaseActivity mRequestingActivity = null;
private String mSelectedAccount = null;
/**
* Get the GPlus singleton
* #return GPlus
*/
public synchronized static MyGooglePlusClient getInstance() {
if (myGPlus == null)
myGPlus = new MyGooglePlusClient();
return myGPlus;
}
public boolean login(BaseActivity requester) {
Log.w(LOG_TAG, "Starting login...");
if (mRequestingActivity != null) {
Log.w(LOG_TAG, "Login attempt already in progress.");
return false; // Cannot launch a new request; already in progress
}
mRequestingActivity = requester;
if (mSelectedAccount == null) {
Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}, false,
null, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE, null, null);
mRequestingActivity.startActivityForResult(intent, BaseActivity.REQUEST_GPLUS_SELECT);
}
return true;
}
public void loginCallback(String accountName) {
mSelectedAccount = accountName;
authorizeCallback();
}
public void logout() {
Log.w(LOG_TAG, "Logging out...");
mSelectedAccount = null;
}
public void authorizeCallback() {
Log.w(LOG_TAG, "User authorized");
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String token = null;
try {
Bundle b = new Bundle();
b.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES, ACTIVITIES_LOGIN);
token = GoogleAuthUtil.getToken(mRequestingActivity,
mSelectedAccount,
"oauth2:server:client_id:"+Constants.GOOGLE_PLUS_SERVER_OAUTH_CLIENT
+":api_scope:" + SCOPES_LOGIN,
b);
} catch (IOException transientEx) {
// Network or server error, try later
Log.w(LOG_TAG, transientEx.toString());
onCompletedLoginAttempt(false);
} catch (GooglePlayServicesAvailabilityException e) {
Log.w(LOG_TAG, "Google Play services not available.");
Intent recover = e.getIntent();
mRequestingActivity.startActivityForResult(recover, BaseActivity.REQUEST_GPLUS_AUTHORIZE);
} catch (UserRecoverableAuthException e) {
// Recover (with e.getIntent())
Log.w(LOG_TAG, "User must approve "+e.toString());
Intent recover = e.getIntent();
mRequestingActivity.startActivityForResult(recover, BaseActivity.REQUEST_GPLUS_AUTHORIZE);
} catch (GoogleAuthException authEx) {
// The call is not ever expected to succeed
Log.w(LOG_TAG, authEx.toString());
onCompletedLoginAttempt(false);
}
Log.w(LOG_TAG, "Finished with task; token is "+token);
if (token != null) {
authorizeCallback(token);
}
return token;
}
};
task.execute();
}
public void authorizeCallback(String token) {
Log.w(LOG_TAG, "Token obtained: "+token);
// <snipped - do some more stuff involving connecting to the server and resetting the state locally>
}
public void onCompletedLoginAttempt(boolean success) {
Log.w(LOG_TAG, "Login attempt "+(success ? "succeeded" : "failed"));
mRequestingActivity.hideProgressDialog();
mRequestingActivity = null;
}
}
I've had this issue for a while and came up with a proper solution.
String token = GoogleAuthUtil.getToken(this, accountName, scopeString, appActivities);
This line will either return the one time token or will trigger the UserRecoverableAuthException.
On the Google Plus Sign In guide, it says to open the proper recovery activity.
startActivityForResult(e.getIntent(), RECOVERABLE_REQUEST_CODE);
When the activity returns with the result, it will come back with few extras in the intent and that is where the new token resides :
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == RECOVERABLE_REQUEST_CODE && responseCode == RESULT_OK) {
Bundle extra = intent.getExtras();
String oneTimeToken = extra.getString("authtoken");
}
}
With the new oneTimeToken given from the extra, you can submit to the server to connect properly.
I hope this helps!
Its too late to reply but it may help to people having same concern in future.
They have mentioned in the tutorial that it will always throw UserRecoverableAuthException
when you invoke GoogleAuthUtil.getToken() for the first time. Second time it will succeed.
catch (UserRecoverableAuthException e) {
// Requesting an authorization code will always throw
// UserRecoverableAuthException on the first call to GoogleAuthUtil.getToken
// because the user must consent to offline access to their data. After
// consent is granted control is returned to your activity in onActivityResult
// and the second call to GoogleAuthUtil.getToken will succeed.
startActivityForResult(e.getIntent(), AUTH_CODE_REQUEST_CODE);
return;
}
i used below code to get access code from google.
execute this new GetAuthTokenFromGoogle().execute(); once from public void onConnected(Bundle connectionHint) and once from protected void onActivityResult(int requestCode, int responseCode, Intent intent)
private class GetAuthTokenFromGoogle extends AsyncTask<Void, Integer, Void>{
#Override
protected void onPreExecute()
{
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
accessCode = GoogleAuthUtil.getToken(mContext, Plus.AccountApi.getAccountName(mGoogleApiClient), SCOPE);
new ValidateTokenWithPhoneOmega().execute();
Log.d("Token -- ", accessCode);
} catch (IOException transientEx) {
// network or server error, the call is expected to succeed if you try again later.
// Don't attempt to call again immediately - the request is likely to
// fail, you'll hit quotas or back-off.
return null;
} catch (UserRecoverableAuthException e) {
// Recover
startActivityForResult(e.getIntent(), RC_ACCESS_CODE);
e.printStackTrace();
} catch (GoogleAuthException authEx) {
// Failure. The call is not expected to ever succeed so it should not be
// retried.
authEx.printStackTrace();
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
}
}
I have got around this issue by using a web based login. I open a url like this
String url = "https://accounts.google.com/o/oauth2/auth?scope=" + Scopes.PLUS_LOGIN + "&client_id=" + webLoginClientId + "&response_type=code&access_type=offline&approval_prompt=force&redirect_uri=" + redirect;
The redirect url then handles the response and returns to my app.
In terms of my findings on using the Google Play Services, I've found:
HTC One is 3.1.59 (736673-30) - not working
Galaxy Note is 3.1.59 (736673-36) - not working
Nexus S is 3.1.59 (736673-34) - works
And I'd like to be involved in the chat that is occurring, however I don't have a high enough reputation to do so.
I've experienced the same issue recently - it appears to be device-specific (I had it happen every time on one S3, but on another S3 running the same OS it didn't happen, even with the same account). My hunch is that it's a bug in a client app, either the G+ app or the Google Play Services app. I managed to solve the issue on one of my devices by factory resetting it (a Motorola Defy), then reinstalling the Google Play Services app, but that's a completely useless solution to tell to users.
Edit (6th Aug 2013): This seems to have been fixed for me without any changes to my code.
The first potential issue I can see is that you are calling GoogleAuthUtil.getToken() after you get the onConnected() callback. This is a problem because requesting an authorization code for your server using GoogleAuthUtil.getToken() will always show a consent screen to your users. So you should only get an authorization code for new users and, to avoid showing new users two consent screens, you must fetch an authorization code and exchange it on your server before resolving any connection failures from PlusClient.
Secondly, make sure you actually need both a PlusClient and an authorization code for your servers. You only need to get a PlusClient and an authorization code if you are intending to make calls to the Google APIs from both the Android client and your server. As explained in this answer.
These issues would only result in two consent dialogs being displayed (which is clearly not an endless loop) - are you seeing more than two consent dialogs?
I had a similar problem where an apparent auth loop kept creating {read: spamming} these "Signing In..." and Permission request dialogs while also giving out the discussed exception repeatedly.
The problem appears in some slightly-modified example code that I (and other like me, I suspect) "cargo-culted" from AndroidHive. The solution that worked for me was ensuring that only one background token-retrieval task runs at the background at any given time.
To make my code easier to follow, here's the auth flow in my app (that is almost identical to the example code on AndoidHive): Activity -> onConnected(...) -> getProfileInformation() -> getOneTimeToken().
Here's where getOneTimeToken() is called:
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
getOneTimeToken(); // <-------
...
Here's my getOneTimeToken():
private void getOneTimeToken(){
if (task==null){
task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
LogHelper.log('d',LOGTAG, "Executing background task....");
Bundle appActivities = new Bundle();
appActivities.putString(
GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,
ACTIVITIES_LOGIN);
String scopes = "oauth2:server" +
":client_id:" + SERVER_CLIENT_ID +
":api_scope:" + SCOPES_LOGIN;
String token = null;
try {
token = GoogleAuthUtil.getToken(
ActivityPlus.this,
Plus.AccountApi.getAccountName(mGoogleApiClient),
scopes,
appActivities
);
} catch (IOException transientEx) {
/* Original comment removed*/
LogHelper.log('e',LOGTAG, transientEx.toString());
} catch (UserRecoverableAuthException e) {
/* Original comment removed*/
LogHelper.log('e',LOGTAG, e.toString());
startActivityForResult(e.getIntent(), AUTH_CODE_REQUEST);
} catch (GoogleAuthException authEx) {
/* Original comment removed*/
LogHelper.log('e',LOGTAG, authEx.toString());
} catch (IllegalStateException stateEx){
LogHelper.log('e',LOGTAG, stateEx.toString());
}
LogHelper.log('d',LOGTAG, "Background task finishing....");
return token;
}
#Override
protected void onPostExecute(String token) {
LogHelper.log('i',LOGTAG, "Access token retrieved: " + token);
}
};
}
LogHelper.log('d',LOGTAG, "Task setup successful.");
if(task.getStatus() != AsyncTask.Status.RUNNING){
task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR); //double safety!
} else
LogHelper.log('d',LOGTAG,
"Attempted to restart task while it is running!");
}
Please note that I have a {probably redundant} double-safety against the task executing multiple times:
if(task .getStatus() != AsyncTask.Status.RUNNING){...} - ensures that the task isn't running before attempting to execute it.
task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);- makes sure that copies of this task are "synchronized" (i.e. a queue is in place such that only one task of this type can executed at a given time).
P.S.
Minor clarification: LogHelper.log('e',...) is equivalent to Log.e(...) etc.
you should startactiviy in UI thread
try {
....
} catch (IOException transientEx) {
....
} catch (final UserRecoverableAuthException e) {
....
runOnUiThread(new Runnable() {
public void run() {
startActivityForResult(e1.getIntent(), AUTH_CODE_REQUEST);
}
});
}
Had the same bug with infinite loop of permission request. For me it was because time on my phone was shifted. When I check detect time automatically this bug disappeared. Hope this helps!
I'm doing authentication of android app against an app engine server, basically following this post: http://blog.notdot.net/2010/05/Authenticating-against-App-Engine-from-an-Android-app.
It appears that the cookie that I get at the end of the process is no good - I'm getting 401, so I tried copying the cookie and testing it in the browser, and still getting 401. When copying the browser cookie to the android app, the request works.
How could I be getting an invalid cookie? I've even tried invalidating the tokens, but still getting the same result...
Don't bother doing this yourself. Use this: http://loopj.com/android-async-http/
For some reason this worked: I changed the URL for the initial cookie request from https to http, then changed it back.
But in the end I decided to change my implementation and go with loopj as alistair suggested. The result is far more elegant. This is my login activity (note that I'm connecting the client to a persistent cookie storage given by loopj api):
public class AccountList extends ListActivity {
protected AccountManager accountManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
accountManager = AccountManager.get(getApplicationContext());
Account[] accounts = accountManager.getAccountsByType("com.google");
this.setListAdapter(new ArrayAdapter<Account>(this, R.layout.list_item, accounts));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Account account = (Account)getListView().getItemAtPosition(position);
accountManager.invalidateAuthToken("com.google", null);
accountManager.getAuthToken(account, "ah", null, this, new GetAuthTokenCallback(), null);
}
private class GetAuthTokenCallback implements AccountManagerCallback<Bundle> {
public void run(AccountManagerFuture<Bundle> result) {
AsyncHttpClient client = new AsyncHttpClient();
PersistentCookieStore myCookieStore = new PersistentCookieStore(getBaseContext());
client.setCookieStore(myCookieStore);
try {
Bundle bundle;
bundle = result.getResult();
Intent intent = (Intent)bundle.get(AccountManager.KEY_INTENT);
if(intent != null) {
// User input required
startActivity(intent);
} else {
String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
String url = "http://myapp.appspot.com/_ah/login?continue=http://localhost/&auth=" + token;
client.post(url, new AsyncHttpResponseHandler());
Intent backToMainActivity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(backToMainActivity);
}
} catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Because loopj gives persistent cookie storage, all I have to do in another activity is to initialize a client and connect it with the persistent cookie storage. This gives the new client all of the cookies I got from the login activity. Initialization looks something like this:
AsyncHttpClient client = new AsyncHttpClient();
client.setCookieStore(new PersistentCookieStore(this));
BTW & FYI: The loopj library uses the SharedPreferences API in order to store the cookies, and wraps it nicely as PersistentCookieStore.
dont know what httpclient you are using.
maybe it will help to read the apache docs on cookies...