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.
Related
I have been following the dated and limited documentation on the E*Trade developer site and with help from some other stack overflow posts.
I am pretty certain that I have retrieved a good access token and secret. I have been following their snippets
request = new ClientRequest(); // Instantiate ClientRequest
request.setEnv(Environment.SANDBOX); // Use sandbox environment
request.setConsumerKey(oauth_consumer_key); // Set consumer key
request.setConsumerSecret(oauth_consumer_secret); // Set consumer secret
request.setToken(oauth_access_token);
request.setTokenSecret(oauth_access_token_secret);
AccountsClient account_client = new AccountsClient(request);
I also tried with:
MarketClient client = new MarketClient(request);
ArrayList<String> list = new ArrayList<>();
list.add("AAPL");
QuoteResponse response = client.getQuote(list, Boolean.FALSE, DetailFlag.ALL);
In all case, it returns a 401 code and a message of <Error> message>Unauthorized request</message></Error>
Is this something on the E-Trade end? Or something with my implementation of their snippets? I have reached out to E-Trade but thought I'd post here with the hope of a resolution.
I am trying to build authentication flow in our app for facebook in java. I am using facebook4j library.
My corresponding code is as follows -
public String authenticate() throws IOException {
Facebook facebook = new FacebookFactory().getInstance();
String redirectURL = facebook.getOAuthAuthorizationURL("http://localhost:9099/default/facebook/verify.html");
servletResponse.sendRedirect(redirectURL);
return null;
}
public String verify() throws Exception {
String code = servletRequest.getParameter("code");
Facebook facebook = new FacebookFactory().getInstance();
AccessToken accessToken = facebook.getOAuthAccessToken(code);
String token = accessToken.getToken();
servletResponse.getWriter().write(token);
return null;
}
I am getting error after redirection on this line -
AccessToken accessToken = facebook.getOAuthAccessToken(code);
The error is as follows -
FacebookException{statusCode=400, errorType='OAuthException', errorMessage='redirect_uri isn't an absolute URI. Check RFC 3986.', errorCode=191, errorSubcode=-1, version=2.2.2}
at facebook4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:179)
at facebook4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at facebook4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:97)
at facebook4j.auth.OAuthAuthorization.getOAuthAccessToken(OAuthAuthorization.java:107)
redirectURL that I am getting from facebook in first call is -
https://www.facebook.com/dialog/oauth?client_id=4161XXXXXX6389&redirect_uri=http%3A%2F%2Flocalhost%3A9099%2Fdefault%2Ffacebook%2Fverify.html&scope=email,public_profile,user_friends
tried without using encoding too -
https://www.facebook.com/dialog/oauth?client_id=4161XXXXXX6389&redirect_uri=http://localhost:9099/default/facebook/verify.html&scope=email,public_profile,user_friends
It is redirecting properly to 'verify' having url something like -
http://localhost:9099/default/facebook/verify.html?code=AQCE4aaIpE_c94J3NVNjge_YL_OP84vPIgUauvfRRXNCj_FOK8U2kfSxfKGrjWnFL1dqMeM8q22M6UaVbGsTpTQOQmjxYILdFHKFiSFd0Ycf_ByBE9rNX_yxvFnJ3RNLf7bjCT4C1uXuuqCXHZjVNN1lBb3LWUHz7eNkq0r8K14x7ZEVIWjbll-Vqys1FZuCIVDBrI4StoYkZR1rpCsoSqq7VdCIX3zawnw_nbPZBZU7iUeZJiBbahYjWkHIn47b9AQb3hZxxpe4xxXHXfDsP_h2fhC1YYioJbwGq4QbnWpUrP7aF-0Q_wF71zn4txCQLd4#=
facebook4j.properties
oauth.appId=416XXXXXXXXX389
oauth.appSecret=9ed3XXXXXXb6acXXXXXXXXc7acXXXX5
oauth.permissions=email,public_profile,user_friends
My Facebook App basic settings are -
The important advanced settings are -
I am totally aware that similar question has been posted earlier multiple times. I have gone through almost every question & I tried almost everything suggested to resolve this issue. But due to some reason it is not working. I decided to post my problem here after spending 3 days on the same issue.
I would highly appreciate if someone points out where exactly am I going wrong.
The redirect_uri parameter has to be specified when exchanging the code for a token as well (and has to be the same as specified earlier in the login dialog call).
I’d assume that since you are using new FacebookFactory().getInstance() in your second method, that is not the case. Take a look at the basic implementation here, https://github.com/roundrop/facebook4j-oauth-example/tree/master/src/main/java/facebook4j/examples/signin
In SignInServlet, the Facebook object instance is stored into the session, and then in CallbackServlet that same instance is retrieved and used again. Therefor, it still holds the redirect_uri value that was initially used when the Auth dialog was called, and will re-use that same value when exchanging the code for a token.
I am new to OAuth and I'm developing an Android app that requires it and I'm using the signpost library.
I believe I have it all working up to the point where I can get the token using
String token = uri.getQueryParameter("oauth_token");
Which returns correctly however the very next line
String verifier = uri.getQueryParameter("oauth_verifier");
returns null. I have debugged and inspected uri which is initialized as
Uri uri = this.getIntent().getData();
And it does not appear to have a key "oauth_verifier"
The verifier being null causes an OAuthExpectationFailedException when I try the ofllowing line
provider.retrieveAccessToken(consumer, verifier);
Can anyone help me figure out why the verifier is null I am using a callback not OOB.
I have seen in other questions and guides the likes of this in the response:
dat=myapp://twitter?oauth_token=tJpJHOOwoTGMwdvHyYbfX2tyHKOp0Y2kdRRZf3sM&
oauth_verifier=xc49oM8eVVmK46ZSLz2RMT2uqXn3SxrMxf5ZAMXaD2Y
Mine is similar but without the ouath_verifier key.
Here is where I send the initial intent which works and I get a return
String clientKey = "xxxxxxx";
String clientSecret = "yyyyyyyyy";
CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(clientKey,clientSecret);
provider = new CommonsHttpOAuthProvider(URL_Request_Token,
URL_Access_Token,
URL_Authorize";
provider.setOAuth10a(true);
try {
String authUrl = provider.retrieveRequestToken(consumer,CALLBACK_URI.toString());
String token = consumer.getToken();
String secret = consumer.getTokenSecret();
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
}
Any help is much appreciated
A problem I had while developing a twitter interaction sample is that I forgot to set a callback url from the twitter app console.
If you don't do that, your application won't be redirected and so it won't be able to grap the verifier token.
PROMO MODE ON
However, if you feel particularly brave, I've been working on this library PostManLib lately and I am looking for beta testers. It should handle all the async oauth interaction using the well know scribe library under the hood.
PROMO MODE OFF
I am trying to implement the rest api sample given in the salesforce site link below.
http://wiki.developerforce.com/page/Getting_Started_with_the_Force.com_REST_API
I have set up project as said in the link, but when I am executing the project I am getting an error as "Error - no access token". When I do debug, I came to know that the variable accessToken is null.
String accessToken = (String)
request.getSession().getAttribute("ACCESS_TOKEN");
I am bit confused about this problem.
Please help me in this regard.
It seems you are missing this part in your code:
// Set a session attribute so that other servlets can get the
// access token
request.getSession().setAttribute(ACCESS_TOKEN, accessToken);
// We also get the instance URL from the OAuth response, so set it
// in the session too
request.getSession().setAttribute(INSTANCE_URL, instanceUrl);
I want to get a home timeline from twitter and I was able to get the home timeline using twitter4j and oauth authentication method
ConfigurationBuilder confBuilder = new ConfigurationBuilder();
confBuilder.setOAuthAccessToken(accessToken.getToken())
.setOAuthAccessTokenSecret(accessToken.getTokenSecret())
.setOAuthConsumerKey(key)
.setOAuthConsumerSecret(secret);
Twitter twit = new TwitterFactory(confBuilder.build()).getInstance();
User user = twitter.verifyCredentials();
List<Status> statuses = twitter.getHomeTimeline();
but the result is not in the form of .xml or JSON. i also tried
WebResource resource = client.resource("https://api.twitter.com/1/statuses/user_timeline.json");
but all I get is GET https://api.twitter.com/1/statuses/user_timeline.json returned a response status of 401 Unauthorized
I googled many times but I just cant get it right. Please I need a sample java code of how to do it. Complete code that can run right away would be really helpful as I got a lot of partially coded program and just couldnt get it to work. thank you in advance
OK, so after looking at the release notes for the 2.2.x versions, it appears there is a way to get the JSON representation from Twitter4J, but it's disabled by default since it uses some extra memory.
So, you need to:
Enable the JSONStore using the jsonStoreEnabled config option
Get the JSON representation of a request using the getRawJson method
Sorry there's no code example, I haven't tried it myself.
401 Unauthorized:
Authentication credentials were missing or incorrect.
You need to authenticate before you perform the query.