I am receiving error messages while working with Twitter4J:
java.lang.IllegalStateException: Access token already available.
twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:112)
twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:104)
twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:276)
twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:269)
[...]
This exception is thrown while calling the method Twitter.getOAuthRequestToken(). I want to get the Authorization URL to authenticate the next user.
How am I possible to solve this problem? I only put the OAuthConsumerKey, the OAuthConsumerSecret, the OAuthAccessToken and the OAuthAccessTokenSecret to the Twitter4J properties. But how do I receive the authorization URL to authenticate a new user?
Thanks and greetings,
Martin
Sorry.
I was setting an Access Token hard coded by the Configuration Builder.
Removed it, works now.
You need to create a new instance of twitter and null it's accessToken and accessTokenSecret fields before requesting new access token.
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(TWITTER_CONSUMER_KEY)
.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET)
.setOAuthAccessToken(null)
.setOAuthAccessTokenSecret(null);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
Related
I am using Scribe for oauth to get access_token and refresh_token for the auth_code. It worked well for the first authentication.
When I disabled the credentials in my application, the tokens are still existing with the Gmail connected apps for my application.
When I re-enable the oauth, I am getting only valid new access_token for the new auth_code. But the refresh_token is null.
I tried to replicate the same with oauthplayground, there I could see valid refresh and access tokens, while playground tokens still existed in the google connected apps.
here is the code I implemented with scribe-1.3.0 API
OAuthRequest oAuthRequest = new OAuthRequest(Verb.POST, "https://accounts.google.com/o/oauth2/token");
oAuthRequest.addBodyParameter("client_id", SMTP_OAUTH_CLIENT_ID);
oAuthRequest.addBodyParameter("client_secret", SMTP_OAUTH_CLIENT_SECRET);
oAuthRequest.addBodyParameter("scope", scope);
oAuthRequest.addBodyParameter("redirect_uri", GoogleApi.getRedirectURL());
oAuthRequest.addBodyParameter("code", authCode);
oAuthRequest.addBodyParameter("grant_type", "authorization_code");
Response response = oAuthRequest.send();
Here is the similar code tried with googleapi-client-1.20, the result is still same.
GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(
new NetHttpTransport(),
new JacksonFactory(),
SMTP_OAUTH_CLIENT_ID, SMTP_OAUTH_CLIENT_SECRET,
authCode,
GoogleApi.getRedirectURL())
.execute();
Credential gcredential = new GoogleCredential
.Builder()
.setTransport(new NetHttpTransport.Builder().build())
.setJsonFactory(new JacksonFactory())
.setClientSecrets(SMTP_OAUTH_CLIENT_ID, SMTP_OAUTH_CLIENT_SECRET)
.build()
.setFromTokenResponse(tokenResponse);
gcredential.refreshToken();
System.out.println(gcredential.getRefreshToken());
Can anyone help me where I am going wrong?
Thanks for your time in looking at this issue.
When re-authenticating you need to set these parameters
access_type=offline and approval_prompt=force
then you will recieve refresh_token
Below is an example URL
https://accounts.google.com/o/oauth2/auth?client_id=CLIENT_ID&scope=SCOPE&redirect_uri=REDIRECT_URL&response_type=code&access_type=offline&approval_prompt=force
Im trying to update twitter status using java with Scribe library (1.3).
Asking for a proctected resource as in the example works fine. (https://github.com/fernandezpablo85/scribe-java/blob/master/src/test/java/org/scribe/examples/TwitterExample.java)
However, I get the next error when im trying to write a tweet:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot get String from a null object
at org.scribe.utils.Preconditions.check(Preconditions.java:80)
at org.scribe.utils.Preconditions.checkNotNull(Preconditions.java:27)
at org.scribe.utils.StreamUtils.getStreamContents(StreamUtils.java:20)
at org.scribe.model.Response.parseBodyContents(Response.java:41)
at org.scribe.model.Response.getBody(Response.java:67)
at model.TwitterExample.main(TwitterExample.java:84)
Highlight code parts:
OAuthService service = new ServiceBuilder()
.provider(TwitterApi.Authenticate.class)
.apiKey("------------------------------")
.apiSecret("--------------------------------")
.build();
Scanner in = new Scanner(System.in);
// Obtain the Request Token
Token requestToken = service.getRequestToken();
Verifier verifier = new Verifier(in.nextLine());
// Trade the Request Token and Verfier for the Access Token
Token accessToken = service.getAccessToken(requestToken, verifier);</java>
String tweet = URLEncoder.encode("First Tweet","UTF-8");
String urlTweet="http://api.twitter.com/1.1/statuses/update.json?status="+tweet;
System.out.println("request: "+urlTweet);
OAuthRequest request2 = new OAuthRequest(Verb.POST, urlTweet);
service.signRequest(accessToken, request2);
System.out.println("REQUEST: " + request2.getUrl());
Response response2 = request2.send();
System.out.println(response2.getBody());
This exception throws in "response2.getBody()" print.
I have not been able to find the right solution to my problem in your discussions and external forums, so any help is appreciated.
Thank you in advance!
Try checking response2.getCode() before response2.getBody(), maybe you're getting an error (such a 403 - forbidden) and you're ignoring it.
Hope it helps.
Ok, I got it.
I noticed that the way requests works on twitter have changed just a month ago, and now it has to be used https instead of http.
I did some adjustments in my code before this question in reference to this, like using
.provider(TwitterApi.Authenticate.class)
instead of
.provider(TwitterApi.class).
Even so, I did not change this sentence of my code, which was the reason of my error.
String urlTweet="http://api.twitter.com/1.1/statuses/update.json?status="+tweet;
to
String urlTweet="https://api.twitter.com/1.1/statuses/update.json?status="+tweet;
I hope that if someone comes here with same problem can solve it with this relevant info.
https://github.com/leleuj/pac4j/issues/24
https://github.com/juliendangers/pac4j/commit/72d025e219dd11f854ecf1f8156e48f688d55615
Thanks eltabo for taking me to the right direction.
I am implementing twitter in my application using scribe.
After the user authenticate my app and is redirected to new url,
I got the oauth_token and oauth_verifier but could not figure out how to generate oauth_token and oauth_secret from it.
Kindly resolve the issue and thank you in advance!!!
I've solved the problem just make a new service builder(as in the example) in the redirected page and use the oauth_token and oauth_verifier u'll get when u will be redirected to new page like this
Token requestToken = new Token(request.getParameter("oauth_token"),request.getParameter("oauth_verifier"));
Verifier verifier = new Verifier(request.getParameter("oauth_verifier"));
rest is same as in example.
See the Twitter example.
The oauth token and verifier should be what you need to request an access token and access protected resources.
I need my Java Twitter application to be able to follow a user in twitter. When I pass it the user ID as a string, the application follow it automatically. I couldn't find the method that can do that in Twitter4j.
No need for id. It will work with username as well.
mTwitter.createFriendship("dj")
Problem solved ,you can follow a user using twitter.createFriendship("twitter id"); method
The following configuration will do it:
ConfigurationBuilder cb =new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("******")
.setOAuthConsumerSecret("******")
.setOAuthAccessToken("*******")
.setOAuthAccessTokenSecret("********");
//In case of proxy
//cb.setHttpProxyHost("******").setHttpProxyPort(8080);
TwitterFactory twitterFactory=new TwitterFactory(cb.build());
Twitter twitter=twitterFactory.getInstance();
twitter.createFriendship("twitter id");
I'm using scribe for making an app that has oauth support. I didn't found problems With Twitter, but when using facebook I have problems...
This is the code that works on twitter oauth
OAuthService s = /* ... Facebook oauth init ... */
final Token requestToken = s.getRequestToken();
final String authURL = s.getAuthorizationUrl(requestToken);
It gives me an error at the second line:
12-20 10:01:31.475: E/AndroidRuntime(5405): java.lang.UnsupportedOperationException: Unsupported operation, please use 'getAuthorizationUrl' and redirect your users there
12-20 10:01:31.475: E/AndroidRuntime(5405): at org.scribe.oauth.OAuth20ServiceImpl.getRequestToken(OAuth20ServiceImpl.java:45)
I know that it says that I might use getAuthorizationUrl... But I have to pass a requestToken...
Could you please help me?
It would be helpful any example with Scribe and Facebook
Thanks!
PS: Same problem with Windows Live ! =(
EDIT:
I have been looking at the source code of the Scribe library and I found something
https://github.com/fernandezpablo85/scribe-java/blob/master/src/main/java/org/scribe/oauth/OAuth20ServiceImpl.java
Here we can see that I can call the getAuthorizationUrl(...) with null parameter because it doesn't use it.... But I think the prioblem now is that the config isn't filled...
here is how I initialize facebook service:
new ServiceBuilder()
.provider(FacebookApi.class)
.apiKey(....)
.apiSecret(....)
.scope("email,offline_access")
.callback("oauth://facebook")
.build();
Is this correct?
Thanks!
private static final Token EMPTY_TOKEN = null;
OAuthService service = new ServiceBuilder()
.provider(FacebookApi.class)
.apiKey(apiKey)
.apiSecret(apiSecret)
.callback("http://www.example.com/oauth_callback/")
.build();
String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
All you now need to redirect user to this URL and let him verify them self to get code from facebok.
There are a good amount of example with very good documentation for almost all major Oath
system
here is for Facebook
FacebookExample
For all major providers
Scribe Example Directory
Edit
After looking at the discussion my suggestion is to get a full understanding about Oauth1 and Oauth2.
You've got it all wrong. OAuth 2 Protocol never returns a request token like OAuth 1.
Oauth 1 does an HTTP POST request and returns an unauthorized request token. Then, you will have to authorize your unauthorized token to receive an authorized token (That's 2 HTTP call).
Oauth 2, on the other hand, doesn't have a request token flow, you will need to do an HTTP GET for an authorization token (1 HTTP call only). Hence why Scribe says that you need to call getAuthorizedUrl.
See this Facebook Example, to see how to retrieve an authorized token using OAuth 2.