How can I get the user name, email, location, avatar, etc., of an authenticated user of Twitter in Android via the API?
I wrote the code below, but it always returns null at twitter.showUser(twitter.getId());
public User getUserInfo(Object accessToken)
{
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(mConsumer.getConsumerKey());
configurationBuilder.setOAuthConsumerSecret(mConsumer.getConsumerSecret());
twitter4j.Twitter twitter = new TwitterFactory(configurationBuilder.build()).getInstance();
try
{
twitter.setOAuthAccessToken((AccessToken) accessToken);
return twitter.showUser(twitter.getId());
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
I found another question here. People said that unable to retrieve email address of authenticated user of Twitter via api. So, How about other information such as fullname, avatar, phone number (if have),...?
Related
I'm using the oauth2-essentials library because it was one of the recommended oauth libraries on the uber developers site, and it has been recently updated.
My code looks like this:
executor = new HttpUrlConnectionExecutor();
OAuth2AuthorizationProvider provider = new BasicOAuth2AuthorizationProvider(
URI.create("https://login.uber.com/oauth/v2/authorize"),
URI.create("https://login.uber.com/oauth/v2/token"),
new Duration(1,0,3600) /* default expiration time in case the server doesn't return any */);
OAuth2ClientCredentials credentials = new BasicOAuth2ClientCredentials(
getString(R.string.uberClientId), getString(R.string.uberSecret));
uberOAuthClient = new BasicOAuth2Client(
provider,
credentials,
new LazyUri(new Precoded("my redirect url")) /* Redirect URL */);
generateUberOAuthToken("my phone number", "my password");
}
public void generateUberOAuthToken(final String uName, final String password){
new Thread() {
public void run() {
try {
uberOAuthToken = new ResourceOwnerPasswordGrant(
uberOAuthClient, new BasicScope("profile"), uName, password).accessToken(executor);
}
catch (Exception e){
e.printStackTrace();
}
}
}.start();
}
The exception: org.dmfs.httpessentials.exceptions.UnauthorizedException: Authentication at 'https://login.uber.com/oauth/v2/token' failed. is always thrown. I've tried removing the redirect url so it should use the default from my dashboard, and I've tried added 1 and/or dashes to the phone number. The exception is always thrown when I request an access token. I know my account is setup correctly because this works fine in iOS. I feel like I must be missing something obvious. Anyone else run into this issue?
The token api did not recognize my phone number as a valid login parameter. It worked when I used my email instead.
I'm trying to create a new ParseUser using a Google+ SignIn. While I'm able to retrieve the access token successfully from Google, I get a ParseException(InvalidSession).
I'll post a few snippets that are relevant.
This is how im getting the AccessToken from Google
final String SCOPES = "https://www.googleapis.com/auth/plus.login ";
token = GoogleAuthUtil.getToken(
MainActivity.this,
Plus.AccountApi.getAccountName(mGoogleApiClient),
"oauth2:" + SCOPES);
Making ParseUser
ParseUser.becomeInBackground(token, new LogInCallback()
{
public void done(ParseUser user, ParseException e)
{
Log.i(TAG, "makeParseUser"+"2");
if (user != null)
{
// The current user is now set to user.
/*
user.put("name", s1);
user.put("email",s6);
user.saveInBackground();
*/
}else
{
// The token could not be validated.
Log.i(TAG, "makeParseUser"+e.getLocalizedMessage());
}
}
});
A similar question has been asked here but there doesn't seem to be a proper solution to it.
Currently Parse doesn't support G+ login. Practically it can be done by using Parse cloud code.
ParseUser.becomeInBackground(); expects Parse User token, but not G+ one.
I've wrote some code to allow a user to login to his Twitter account and send Tweet using Twitter4j and following this tutorial.
Now I can also get the tweets of a public account using
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setHttpConnectionTimeout(10000)
.setHttpReadTimeout(10000)
.setOAuthConsumerKey(Config.TWITTER_CONSUMER_KEY)
.setOAuthConsumerSecret(Config.TWITTER_CONSUMER_SECRET)
.setOAuthAccessToken(Utils.getPrefsString(getActivity(),
TwitterPrefsFragment.PREF_KEY_OAUTH_TOKEN, "")) // empty if not authentified
.setOAuthAccessTokenSecret(Utils.getPrefsString(getActivity(),
TwitterPrefsFragment.PREF_KEY_OAUTH_SECRET, "")); // empty if not authentified
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
List<twitter4j.Status> statuses = twitter.getUserTimeline(SOME_PUBLIC_TWITTER_ACCOUNT, new Paging(1, 50));
but this only works when the user is authenticated and the app has the oauth token and secret in the preferences..
How can I get a Twitter public timeline with no Access Token, i.e. without having the user to authenticate?
EDIT
I'm reformulating my question to make it clearer:
I managed to authenticate my Twitter app and a user with the code given here.
Now, if the user is not logged in, how can I get a public timeline? In that case, there is no OAUTH_TOKEN and OAUTH_SECRET, and the request shown above does not work because an empty string is set to ConfigurationBuilder.setOAuthAccessToken and ConfigurationBuilder.setOAuthAccessTokenSecret.
So what is, if it exists, the request to get a public timeline, with no OAUTH_TOKEN and OAUTH_SECRET?
In your case, you should use Application-only authentication.
To do this with Twitter4J, try the following code
ConfigurationBuilder cb = new ConfigurationBuilder();
cb
.setOAuthConsumerKey(<YOUR_CONSUMER_KEY>)
.setOAuthConsumerSecret(<YOUR_CONSUMER_SECRET>)
.setApplicationOnlyAuthEnabled(true); // IMPORTANT: set T4J to use App-only auth
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
OAuth2Token token = twitter.getOAuth2Token();
if (token != null) {
System.out.println("Token Type : " + token.getTokenType());
System.out.println("Access Token: " + token.getAccessToken());
}
ResponseList<Status> list = twitter.getUserTimeline(783214); // Load #twitter's timeline without user login.
Key points of the above sample code:
Call setApplicationOnlyAuthEnabled(true) to enable Application-only authentication.
Get the access Token using getOAuth2Token() instead of getOAuthAccessToken()
This is certainly possible and I have already tried it. If your doubt is only regarding the Access Token and Access Token secret being empty, then you should try to use the Access Token provided in the app page. By app page I mean, the link where you have registered your twitter app.
If you go to dev.twitter.com ,and go to your app settings, you can see a consumer key, consumer secret, access token and access token secret. Make use of these and follow my below code and it should work,
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("B*************Q")
.setOAuthConsumerSecret(
"l*************o")
.setOAuthAccessToken(
"1*************s")
.setOAuthAccessTokenSecret(
"s*************s");
TwitterFactory tf = new TwitterFactory(cb.build());
twitter = tf.getInstance();
try {
List<Status> statuses;
String user;
user = "Replace this with the screen name whose feeds you want to fetch";
statuses = twitter.getUserTimeline(user);
Log.i("Status Count", statuses.size() + " Feeds");
} catch (TwitterException te) {
te.printStackTrace();
}
I used twitter 4j 3.03.jar for this.
How can I get a Twitter public timeline with no Access Token and Secret using Twitter4j?
Oh, that is very simple. YOU CAN'T.
Twitter a a data based company. 99% of the property of the company (I mean what the company owns) is data. It would be contra-productive, to give this data for free out to other people/businesses.
If the thing you want, would be possible, then there would be an easy way to backup the whole twitter database.
That is why they let you register an account for each application, that wants to use the API and limit each account to a certain amount of API calls per time frame. Of course they also want to prevent their network from spam etc.
If you want get tweets without user authenticating, you can use Application-only Authentication, because the user doesn´t need to login.
With Application-only authentication Twitter offers applications the ability to issue authenticated requests on behalf of the application itself (as opposed to on behalf of a specific user)
The application-only auth flow follows these steps:
An application encodes its consumer key and secret into a specially encoded set of credentials.
An application makes a request to the POST oauth2/token endpoint to exchange these credentials for a bearer token.
When accessing the REST API, the application uses the bearer token to authenticate.
NOTE: Because twitter4j has added this feature recently, you should use the last snapshot library.
An example using it:
private ConfigurationBuilder builder;
private Twitter twitter;
private TwitterFactory factory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.init_act_layout);
// setup
builder = new ConfigurationBuilder();
builder.setUseSSL(true);
builder.setApplicationOnlyAuthEnabled(true);
builder.setOAuthConsumerKey(Constants.CONSUMER_KEY);
builder.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
Configuration configuration = builder.build();
factory = new TwitterFactory(configuration);
((MyApp) (MyApp.getApp())).setTFactory(factory);
if (isNeededTwitterAuth()) {
twitter = factory.getInstance();
//Get the token async and save it
}
//Search tweets
}
/*
* Checks if twitter access token is already saved in preferences
*
* #return true if auth needed
*/
private boolean isNeededTwitterAuth() {
SharedPreferences settings = getSharedPreferences(Constants.TWITTER_PREFERENCES, Context.MODE_PRIVATE);
String twitterAccesToken = settings.getString("bearerAccessToken", "");
String twitterTokenType = settings.getString("bearerTokenType", "");
return ((twitterAccesToken.length() == 0) && (twitterTokenType.length() == 0));
}
}
To get the bearer token, do it out of Main UI thread to avoid Network exception, f.i. using AsyncTask:
#Override
protected OAuth2Token doInBackground(Void... params) {
OAuth2Token bearerToken = null;
try {
bearerToken = twitter.getOAuth2Token();
} catch (TwitterException e) {
e.printStackTrace();
}
return bearerToken;
}
When you obtain the bearer token, save it:
SharedPreferences appSettings = getSharedPreferences(Constants.TWITTER_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = appSettings.edit();
prefEditor.putString("bearerAccessToken", result.getAccessToken());
prefEditor.putString("bearerTokenType", result.getTokenType());
prefEditor.commit();
And to use the bearer token:
OAuth2Token bearerToken = new OAuth2Token(bearerTokenType, bearerAccesstoken);
twitter.setOAuth2Token(bearerToken);
And search tweets (always out of Main thread):
#Override
protected QueryResult doInBackground(Void... params) {
twitter.setOAuth2Token(bearerToken);
Query query = new Query();
[...]
result = twitter.search(query);
A complete explanation in the blog (in Spanish...)
And a complete example in the twitter4j github
Hope it helps!
So I'm trying to get a list of status objects from a public Twitter timeline ( not my own Twitter timeline or anything that I have admin access to, just a public one from a local organization ) using the Twitter4J library in Android Studio, but I'm getting a little confused by the documentation. I'm running into this error: "Invalid access token format."
I did create a developers account with Twitter and got a consumer key and token, as well as an access token and secret numbers. Those values are saved in a set of private static strings for now. TWITTER_ZOO_ID is a private long with the Twitter ID number for the feed that I want to display. Here's the applicable code that I currently have:
Twitter twitter;
List<Status> statuses = null;
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey( TWITTER_CONSUMER_KEY )
.setOAuthConsumerSecret( TWITTER_CONSUMER_SECRET )
.setOAuthAccessToken( TWITTER_AUTH_TOKEN )
.setOAuthAccessTokenSecret( TWITTER_AUTH_TOKEN_SECRET );
try {
TwitterFactory tf = new TwitterFactory(cb.build());
twitter = tf.getInstance();
twitter.setOAuthConsumer( TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET );
statuses = twitter.getUserTimeline( TWITTER_ZOO_ID );
}
catch( TwitterException e ) {
Log.e( "TwitterListFragment", "Twitter Exception" );
return;
}
for( Status status : statuses )
mAdapter.add( status );
If anyone has a link to a good example for Twitter 1.1 using Twitter4J, or can provide an example of how to get those statuses, I'd really appreciate it. I'm currently using Android Studio and including Twitter4J in Gradle from MavenCentral.
Thank you!
EDIT:
Upon further reading, I've added this additional code without success:
twitter.setOAuthConsumer( TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET );
AccessToken token = new AccessToken( TWITTER_AUTH_TOKEN, TWITTER_AUTH_TOKEN_SECRET );
twitter.setOAuthAccessToken( token );
If you want to get info from a public Twitter timeline, you can use Application-only Authentication, because the user doesn´t need to login, I think it fits you because you don´t use admin rights.
The application-only auth flow follows these steps:
An application encodes its consumer key and secret into a specially
encoded set of credentials.
An application makes a request to the POST
oauth2/token endpoint to exchange these credentials for a bearer token.
When accessing the REST API, the application uses the bearer token to authenticate.
Because twitter4j has added this feature recently, you should use the last snapshot library.
An example using it:
private ConfigurationBuilder builder;
private Twitter twitter;
private TwitterFactory factory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.init_act_layout);
// setup
builder = new ConfigurationBuilder();
builder.setUseSSL(true);
builder.setApplicationOnlyAuthEnabled(true);
builder.setOAuthConsumerKey(Constants.CONSUMER_KEY);
builder.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
Configuration configuration = builder.build();
factory = new TwitterFactory(configuration);
((MyApp) (MyApp.getApp())).setTFactory(factory);
if (isNeededTwitterAuth()) {
twitter = factory.getInstance();
//Get the token async and save it
}
//Search tweets
}
/*
* Checks if twitter access token is already saved in preferences
*
* #return true if auth needed
*/
private boolean isNeededTwitterAuth() {
SharedPreferences settings = getSharedPreferences(Constants.TWITTER_PREFERENCES, Context.MODE_PRIVATE);
String twitterAccesToken = settings.getString("bearerAccessToken", "");
String twitterTokenType = settings.getString("bearerTokenType", "");
return ((twitterAccesToken.length() == 0) && (twitterTokenType.length() == 0));
}
}
To get the bearer token, do it out of Main UI thread to avoid Network exception, f.i. using AsyncTask:
#Override
protected OAuth2Token doInBackground(Void... params) {
OAuth2Token bearerToken = null;
try {
bearerToken = twitter.getOAuth2Token();
} catch (TwitterException e) {
e.printStackTrace();
}
return bearerToken;
}
When you obtain the bearer token, save it:
SharedPreferences appSettings = getSharedPreferences(Constants.TWITTER_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = appSettings.edit();
prefEditor.putString("bearerAccessToken", result.getAccessToken());
prefEditor.putString("bearerTokenType", result.getTokenType());
prefEditor.commit();
And to use the bearer token:
OAuth2Token bearerToken = new OAuth2Token(bearerTokenType, bearerAccesstoken);
twitter.setOAuth2Token(bearerToken);
And search tweets (always out of Main thread):
#Override
protected QueryResult doInBackground(Void... params) {
twitter.setOAuth2Token(bearerToken);
Query query = new Query();
[...]
result = twitter.search(query);
A complete explanation in the blog (in Spanish...)
And a complete example in the twitter4j github
Hope it helps!
I would recommend using the recently updated Twitter SDK (Fabric).
https://docs.fabric.io/android/twitter/twitter.html
Hi I am trying to use the Parse Api's database for my project which requires user accounts that Parse provides. While I was reading the tutorial on how to set up user accounts at
https://parse.com/docs/android_guide#users it stated:
"Enabling email verification in an application's settings allows the application to reserve part of its experience for users with confirmed email addresses. Email verification adds the emailVerified key to the ParseUser object. When a ParseUser's email is set or modified, emailVerified is set to false. Parse then emails the user a link which will set emailVerified to true."
How exactly would you add the emailVerification key = true whenever a user tries to register:
ParseUser user = new ParseUser();
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
// sign up succeeded so go to multiplayer screen
// store the username of the current player
currentUser = username;
final String title = "Account Created Successfully!";
final String message = "Please verify your email before playing";
buildAlertDialog(title, message, true);
} else {
// sign up didnt succed. //TODO: figure out how do deal with error
final String title = "Error Account Creation failed";
final String message = "Account could not be created";
buildAlertDialog(title, message, false);
}
}
});
Go to your parse.com dashboard, go to settings, email settings and switch on the Verify user emails.
No code required.