I am trying to search for public items using Facebook4J, I understad I need an appId AND appSecret which I have, the app token is the these two with a pipe symbol between them (as I understand). I can not understand why I am gett an OAuthError , Please see my code below and precise error code.
facebook4j.conf.ConfigurationBuilder fac = new facebook4j.conf.ConfigurationBuilder();
fac.setDebugEnabled(true)
.setOAuthAppId("appId")
.setOAuthAppSecret("appSecret")
.setOAuthPermissions("email,publish_stream");
fac.setOAuthAccessToken(accessToken);
FacebookFactory ff = new FacebookFactory(fac.build());
Facebook facebook = ff.getInstance();
ResponseList<JSONObject> results = facebook.search("%whatever");
This is the following error code I get. Error code one seems to be unknown API???
Exception in thread "main" message - An unknown error has occurred.
code - 1
Relevant information for error recovery can be found on the Facebook Developers Document:
https://developers.facebook.com/docs/graph-api/using-graph-api/#errors
FacebookException{statusCode=500, errorType='OAuthException', errorMessage='An unknown error has occurred.', errorCode=1, errorSubcode=-1, version=2.4.2}
at facebook4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:179)
at facebook4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
at facebook4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:89)
at facebook4j.FacebookImpl.get(FacebookImpl.java:2742)
at facebook4j.FacebookImpl.search(FacebookImpl.java:2337)
at facebook4j.FacebookImpl.search(FacebookImpl.java:2332)
at Main.facebook4JRequest(Main.java:37)
at Main.main(Main.java:15)
Try using the below code it worked for me.
Facebook facebook = new FacebookFactory().getInstance();
facebook.setOAuthAppId("XXXXXX", "XXXXXXXXXXXX");
String accessTokenString = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
AccessToken at = new AccessToken(accessTokenString);
facebook.setOAuthAccessToken(at);
ResponseList<Post> feeds = facebook.getPosts("%whatever", new Reading().limit(80));
Related
I faced an issue with google pay with stripe. The problem is that I fully
followed the documentation and get an obscure error. I have this onGooglePayResult and i always have Result.Failed with error - " java.lang.RuntimeException: Google Pay failed with error 10 " And error code 2.Feel free to ask i can answer on all your questions.
Main error is java.lang.RuntimeException: Google Pay failed with error 10:. This is coming in GooglePayPaymentMethodLauncher.Result.Failed. I really can't understand why this is producing, I've checked stripe documentation twice, google pay set up and everything, but can't find out.
I mean how to find out what is real error message is, I try to find anything related to this but unfortunatelythere is simply nothing of the kind.
Logcat - error = java.lang.RuntimeException: Google Pay failed with error 10: + error code = 2
private fun onGooglePayResult(
result: GooglePayPaymentMethodLauncher.Result
) {
when (result) {
is GooglePayPaymentMethodLauncher.Result.Completed -> {
// Payment details successfully captured.
// Send the paymentMethodId to your server to finalize payment.
val paymentMethodId = result.paymentMethod.id
presenter.payPlanWithGooglePay(deviceIdentifier, paymentMethodId)
}
GooglePayPaymentMethodLauncher.Result.Canceled -> {
// User cancelled the operation
Timber.d("Cancel")
}
is GooglePayPaymentMethodLauncher.Result.Failed -> {
// Operation failed; inspect `result.error` for the exception
Timber.d("error = ${result.error} + error code = ${result.errorCode}")
}
}
}
I've resolved this issue, was my fault. I forget to add the PUBLISHABLE key from the stripe developer portal.
I use this function to set up Google pay. Just substitute TEST_PUBLISHABLE_KEY with your key in stripe account(Website).
private fun setUpGooglePay(): GooglePayPaymentMethodLauncher {
PaymentConfiguration.init(this, TEST_PUBLISHABLE_KEY)
return GooglePayPaymentMethodLauncher(
activity = this,
config = GooglePayPaymentMethodLauncher.Config(
environment = GooglePayEnvironment.Test,
merchantCountryCode = Constants.GooglePay.Manx.COUNTRY_CODE,
merchantName = UIUtils.getString(R.string.app_name)
),
readyCallback = ::onGooglePayReady,
resultCallback = ::onGooglePayResult
)
}
I am trying to read data from reddit using java. I am using JRAW.
Here is my code:
public class Main {
public static void main(String args[]) {
System.out.println('a');
String username = "dummyName";
UserAgent userAgent = new UserAgent("crawl", "com.example.crawl", "v0.1", username);
Credentials credentials = Credentials.script(username, <password>,<clientID>, <client-secret>);
NetworkAdapter adapter = new OkHttpNetworkAdapter(userAgent);
RedditClient reddit = OAuthHelper.automatic(adapter, credentials);
Account me = reddit.me().about();
System.out.println(me.getName());
SubmissionReference submission = reddit.submission("https://www.reddit.com/r/diabetes/comments/9rlkdm/shady_insurance_work_around_to_pay_for_my_dexcom/");
RootCommentNode rcn = submission.comments();
System.out.println(rcn.getDepth());
System.out.println();
// Submission submission1 = submission.inspect();
// System.out.println(submission1.getSelfText());
// System.out.println(submission1.getUrl());
// System.out.println(submission1.getTitle());
// System.out.println(submission1.getAuthor());
// System.out.println(submission1.getCreated());
System.out.println("-----------------------------------------------------------------");
}
}
I am making two requests as of now, first one is reddit.me().about(); and the second is reddit.submission("https://www.reddit.com/r/diabetes/comments/9rlkdm/ shady_insurance_work_around_to_pay_for_my_dexcom/");
The output is:
a
[1 ->] GET https://oauth.reddit.com/api/v1/me?raw_json=1
[<- 1] 200 application/json: '{"is_employee": false, "seen_layout_switch": true, "has_visited_new_profile": false, "pref_no_profanity": true, "has_external_account": false, "pref_geopopular": "GL(...)
dummyName
[2 ->] GET https://oauth.reddit.com/comments/https%3A%2F%2Fwww.reddit.com%2Fr%2Fdiabetes%2Fcomments%2F9rlkdm%2Fshady_insurance_work_around_to_pay_for_my_dexcom%2F?sort=confidence&sr_detail=false&(...)
[<- 2] 400 application/json: '{"message": "Bad Request", "error": 400}'
Exception in thread "main" net.dean.jraw.ApiException: API returned error: 400 (Bad Request), relevant parameters: []
at net.dean.jraw.models.internal.ObjectBasedApiExceptionStub.create(ObjectBasedApiExceptionStub.java:57)
at net.dean.jraw.models.internal.ObjectBasedApiExceptionStub.create(ObjectBasedApiExceptionStub.java:33)
at net.dean.jraw.RedditClient.request(RedditClient.kt:186)
at net.dean.jraw.RedditClient.request(RedditClient.kt:219)
at net.dean.jraw.RedditClient.request(RedditClient.kt:255)
at net.dean.jraw.references.SubmissionReference.comments(SubmissionReference.kt:50)
at net.dean.jraw.references.SubmissionReference.comments(SubmissionReference.kt:28)
at Main.main(Main.java:36)
Caused by: net.dean.jraw.http.NetworkException: HTTP request created unsuccessful response: GET https://oauth.reddit.com/comments/https%3A%2F%2Fwww.reddit.com%2Fr%2Fdiabetes%2Fcomments%2F9rlkdm%2Fshady_insurance_work_around_to_pay_for_my_dexcom%2F?sort=confidence&sr_detail=false&raw_json=1 -> 400
... 6 more
As it can been that my first request gives me a response of my username but in the second response i am getting a bad request 400 error.
To check whether my client ID and client secret were working correctly I did the same request using python PRAW library.
import praw
from praw.models import MoreComments
reddit = praw.Reddit(client_id=<same-as-in-java>, client_secret=<same-as-in-java>,
password=<same-as-in-java>, user_agent='crawl',
username="dummyName")
submission = reddit.submission(
url='https://www.reddit.com/r/redditdev/comments/1x70wl/how_to_get_all_replies_to_a_comment/')
print(submission.selftext)
print(submission.url)
print(submission.title)
print(submission.author)
print(submission.created_utc)
print('-----------------------------------------------------------------')
This gives the desired result without any errors so the client secret details must be working.
The only doubt I have is in the user agent creation in java UserAgent userAgent = new UserAgent("crawl", "com.example.crawl", "v0.1", username);.
I followed the following link.
What exactly does the target platform, the unique ID or the version mean. I tried to keep the same format as in the link. Also using the same username as in other places. On the other hand the user_agent in python was a string crawl.
Please tell me if I am missing anything and what could be the issue.
Thank you
P.S. I want to do this in java. not python.
Since your first query is working the credentials are correct. In JRAW don't give the whole URL but only the id in the submission function.
Change this
SubmissionReference submission = reddit.submission("https://www.reddit.com/r/diabetes/comments/9rlkdm/shady_insurance_work_around_to_pay_for_my_dexcom/");
to this
SubmissionReference submission = reddit.submission("9rlkdm");
where the id is the random string after /comment/ in the URL.
Hope this helps.
We are using restfb 1.6.14. I am getting the following error while fetching the public posts.
com.restfb.exception.FacebookOAuthException: Received Facebook error response of
type OAuthException: An unexpected error has occurred. Please retry your reques
t later. (code 2, subcode null)
at com.restfb.DefaultFacebookClient$DefaultGraphFacebookExceptionMapper.
exceptionForTypeAndMessage(DefaultFacebookClient.java:964)
at com.restfb.DefaultFacebookClient.throwFacebookResponseStatusException
IfNecessary(DefaultFacebookClient.java:885)
at com.restfb.DefaultFacebookClient.makeRequestAndProcessResponse(Defaul
tFacebookClient.java:824)
at com.restfb.DefaultFacebookClient.makeRequest(DefaultFacebookClient.ja
va:765)
at com.restfb.DefaultFacebookClient.makeRequest(DefaultFacebookClient.ja
va:729)
at com.restfb.DefaultFacebookClient.fetchConnection(DefaultFacebookClien
t.java:271)
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)
Getting the access token using the following code,
AccessToken accessToken = new
DefaultFacebookClient().obtainAppAccessToken(appid,appsecret);
String token=accessToken.getAccessToken();
Getting public posts using the following source code,
public Connection<Post> publicSearchMessages(String keyword, int limit) {
Connection<Post> messages = fbClient.fetchConnection("search",
Post.class, Parameter.with("q", keyword),
Parameter.with("limit", limit), Parameter.with("type", "post"));
return messages;
}
Why this error occurred? How do I solve this error??
With Graph API 2.0 you are not allowed to search for posts, even public one.
I am using Twitter4j for creating Twitter client with JSP and servets. When I am requesting for access token I am getting the following exception:
java.lang.IllegalStateException: Access token already available.
Then I searched on Stack Overflow. I got this post where in solution the author has written:
I was setting an Access Token hard coded by the Configuration Builder.
But they haven't mentioned how they fixed it.I am also not hardcoding access token. Here is my code
StringBuffer callbackURL = request.getRequestURL();
System.out.println("callbackurl is" + callbackURL);
int index = callbackURL.lastIndexOf("/");
callbackURL.replace(index, callbackURL.length(), "").append("/callback");
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(getServletContext().getInitParameter("consumerKey"))
.setOAuthConsumerSecret(getServletContext().getInitParameter("consumerSecret"));
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
System.out.println("Twitter is" + twitter);
request.getSession().setAttribute("twitter", twitter);
RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
System.out.println("request token is " + requestToken);
request.getSession().setAttribute("requestToken", requestToken);
System.out.println(requestToken.getAuthenticationURL());
response.sendRedirect(requestToken.getAuthenticationURL());
This is the stacktrace
HTTP ERROR 500
Problem accessing /Demo1. Reason:
Access token already available.
Caused by:
java.lang.IllegalStateException: Access token already available.
at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:113)
at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:104)
at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:281)
at com.example.Demo1.doGet(Demo1.java:69)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:565)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:479)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:521)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:227)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1031)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:406)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:186)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:965)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:111)
at org.eclipse.jetty.server.Server.handle(Server.java:349)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:449)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:910)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:634)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:230)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:76)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:609)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:45)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:599)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:534)
at java.lang.Thread.run(Thread.java:679)
I met similar problem recently and I debug the source code line by line. I finally found that the configuration would take multiple sources before its ready. When setting the properties such as consumerKey, consumerSecret, it would set from these lines
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(getServletContext().getInitParameter("consumerKey"))
.setOAuthConsumerSecret(getServletContext().getInitParameter("consumerSecret"));
In addition, twitter4j will scan the classpath and find the property files which defines the related key value pairs. I created this file by following the instruction of the tutorial and I forget to delete this. But in the tutorial, it just told you how to get to access the api with the generated accessToken and accessSecret, which were the cause of the IllegalStatusException.
After I found this issue, and I deleted the accessToken and accessTokenSecret keys in the property file. Then problem solved.
Hope this can help you.
I have faced same problem, that is because the access token is already available in the configuration builder. so you need to set it as null in configuration builder
StringBuffer callbackURL = request.getRequestURL();
System.out.println("callbackurl is" + callbackURL);
int index = callbackURL.lastIndexOf("/");
callbackURL.replace(index, callbackURL.length(), "").append("/callback");
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setOAuthConsumerKey((String) "consumerkey")
.setOAuthConsumerSecret("consumersecret").setOAuthAccessToken(null)
.setOAuthAccessTokenSecret(null)
.setOAuthRequestTokenURL("https://api.twitter.com/oauth/request_token")
.setOAuthAuthorizationURL("https://api.twitter.com/oauth/authorize")
.setOAuthAccessTokenURL("https://api.twitter.com/oauth/access_token");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
System.out.println("Twitter is" + twitter);
request.getSession().setAttribute("twitter", twitter);
RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
System.out.println("request token is " + requestToken);
request.getSession().setAttribute("requestToken", requestToken);
System.out.println(requestToken.getAuthenticationURL());
response.sendRedirect(requestToken.getAuthenticationURL());
with this code am able to run the program properly.
I get the error
com.google.gdata.util.AuthenticationException: Unknown authorization header
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:600) ~[gdata-core-1.0.jar:na]
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:563) ~[gdata-core-1.0.jar:na]
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:552) ~[gdata-core-1.0.jar:na]
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:530) ~[gdata-core-1.0.jar:na]
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:535) ~[gdata-core-1.0.jar:na]
when trying to access the Google Calendar data via their API.
Here is what happens before that error.
1) I authenticate with Google:
final AccessTokenResponse response =
new GoogleAuthorizationCodeGrant(httpTransport,
jsonFactory,
clientId, clientSecret, authorizationCode,
redirectUrl).execute();
final GoogleAccessProtectedResource accessProtectedResource =
new GoogleAccessProtectedResource(
response.accessToken, httpTransport, jsonFactory,
clientId, clientSecret,
response.refreshToken);
LOGGER.debug("response.accessToken: {}", response.accessToken);
this.oauthAccessToken = response.accessToken;
...
2) I read some data via the tasks API:
this.service =
new Tasks(httpTransport, accessProtectedResource,
jsonFactory);
this.service.setApplicationName(this.applicationName);
This seems to work.
3) Then I try to read data from the Google Calendar API:
final OAuthHmacSha1Signer signer = new OAuthHmacSha1Signer();
final GoogleOAuthParameters oauth = new GoogleOAuthParameters ();
oauth.setOAuthConsumerKey("myapp.com");
oauth.setOAuthConsumerSecret(CLIENT_SECRET); // Client secret from "Google API access" page, "Client secret" entry
oauth.setOAuthToken(this.oauthAccessToken); // Access token from step 1
oauth.setOAuthTokenSecret(aAuthorizationCode);
// aAuthorizationCode is taken from the callback URL.
// For http://myapp.com/oauth2callback?code=4/uy8Arb4bhRPwWYSr3QwKPt9lIZkt
// aAuthorizationCode is equal to "4/uy8Arb4bhRPwWYSr3QwKPt9lIZkt" (without quotes)
oauth.setScope(SCOPE_CALENDAR); // https://www.google.com/calendar/feeds/
final CalendarService calendarService =
new CalendarService(APPLICATION_NAME);
calendarService
.setOAuthCredentials(oauth, signer);
LOGGER.debug("calendarService: {}", calendarService);
final URL feedUrl =
new URL(
"http://www.google.com/calendar/feeds/default/allcalendars/full");
final CalendarFeed resultFeed =
calendarService.getFeed(feedUrl, CalendarFeed.class);
At the last line (calendarService.getFeed...) the aforementioned exception occurs.
I have following questions:
1) Is my call
oauth.setOAuthConsumerKey
correct?
I. e. is the "consumer key" equal to "Product name" in the Google API console, or to "Client ID" field (value is something like 42912397129473.apps.googleusercontent.com)
2) Is the setOAuthTokenSecret correct? I. e. is it the code that I get, when Google redirects the user back to my app?
3) If questions 2 and 3 were answered with yes, what else can be the cause of my problem?
Thanks
Dmitri
P. S.: Previously, I could access Google calendar with simple access (i. e. with Google user name and password). However, this is not an option now because users of my app will not want to give away their Google password.
Finally, I solved my problem by following the example at
http://code.google.com/p/gdata-java-client/source/browse/trunk/java/sample/oauth/OAuthExample.java
My advice to all future victims^W users of OAuth: Pay attention to the smallest details in the OAuth tutorials. The OAuth devil lies in details.