Facebook Scores API for Android - java

I'm working on integrating the Leaderboards API of FB with my app. And I'm kinda confused with all these permissions, user and app access tokens, and all that. I would be VERY grateful, if someone could explain to me, how to do it step by step, in a simple language. Assume that I'm really retarded and <14.
I really searched a lot to find a solution, but none of them work for me, and I'm sick of this after all day. I write in JAVA.
Okay, I did manage to get the POST and GET requests in the Graph API Explorer, it all works fine, though now I'm not sure how to get my http request in the app operational:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://graph.facebook.com/me/scores");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("score", "3000"));
try{
post.setEntity(new UrlEncodedFormEntity(pairs));
}
catch(UnsupportedEncodingException e)
{
}
try{
HttpResponse response = client.execute(post);
}
catch (IOException e1)
{
}
Another update: it had to be done with AsyncTask. And so I did, everything is almost fine, but this action requires an access token. I've searched A LOT, and I've found tones of information about access tokens, but none of which tells me, how to do it programmatically. What exactly do I have to do, to pass the access token to a HTTP request? (I've set the permissions:
authButton.setReadPermissions(Arrays.asList("user_likes", "user_status", "user_location", "user_birthday",
"user_activities", "user_games_activity"));
}

Facebook has an entire section on working with Android. https://developers.facebook.com/android/
Consider using the official Android SDK so that you don't have to handle authentication an re-write the wheel. https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android/3.0/
Once done that see how this Android sample works https://developers.facebook.com/docs/tutorials/androidsdk/3.0/games/
If you want to do it without the SDK, it is still in your best interests to understand how Facebook does authentication using their SDK so you can build your own https://developers.facebook.com/docs/tutorials/androidsdk/3.0/games/authenticate/
Access tokens are the keys allowed by a user once they have granted access to your application
See more info at https://developers.facebook.com/docs/howtos/androidsdk/3.0/login-with-facebook/

Related

Migrate OOB in HTTP POST request to googleapis

We are making use of this end point - https://www.googleapis.com/oauth2/v4/token
to get the access token.
We make use of apace HTTP classes to make a POST request to this end point in this way -
HttpPost httpPost = new HttpPost(GET_ACCESS_TOKEN_API);
StringBuilder blr = new StringBuilder().append(CLIENT_ID).append("=")
.append((String) accountCredentials.get(CLIENT_ID)).append("&")
.append(CLIENT_SECRET).append("=")
.append((String) accountCredentials.get(CLIENT_SECRET))
.append("&").append(REFRESH_TOKEN).append("=")
.append((String) accountCredentials.get(REFRESH_TOKEN))
.append("&grant_type=refresh_token")
.append("&redirect_uri=urn:ietf:wg:oauth:2.0:oob");
// The message we are going to post
StringEntity requestBody = new StringEntity(blr.toString());
// the default content-type sent to the server is
// application/x-www-form-urlencoded.
requestBody.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(requestBody);
// Make the request
HttpResponse response = HttpUtils.getHttpClient().execute(httpPost);
There has been a recent intimation from google to migrate from out-of-band as they have plans to deprecate this.
We make use of it this way as you can see in the code above -append("&redirect_uri=urn:ietf:wg:oauth:2.0:oob");
GET_ACCESS_TOKEN_API is https://www.googleapis.com/oauth2/v4/token.
I saw some posts mentioning that we have to replace this redirect_uri to localhost.
Can someone explain exactly how this works and what change needs to be done to migrate this successfully ? I tried searching through the documentation to see if there any sample examples but couldn't find anything that matches our use case.
I am referring to this site -
https://developers.google.com/api-client-library/java/google-oauth-java-client/support
I tried to browse through samples, guides, but it mostly talks about different API's. I didn't find the github links that much useful.
Any help would be much appreciated.

Getting Access denied if call API without call the official website

I'm Benjamin, currently study in IT and doing a simple application for Final Year Project.
The simple application is calling Third Party API (An fashion products company) and returns product description, stock level and etc to users.
First, I don't have any official API documents and everything starts from scratch.
I have been using java - CloseableHttpClient to call an API with the method GET.
Coding works fine BUT I met an error that "no response" or Access Denied if I tried to call the API directly. (without any cookies or with existing cookies from the official website)
Then I tried with a browser(any) to hit the API link, it will return Access Denied
But when I tried with a browser and hit the official website without any login, and hit again the API then able to get responses.
I have been tried to passing the cookies that returned from the official website but still no responses when I call/hit the API link on java code or Postman.
Answer for why calling an API that doesn't have any official documentation as below:
This is an FYP in University, API is selected and provided by University Lecturer.
My code as below :
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultCookieStore(cookieStoreNew)
.setUserAgent("Mozilla/5.0").build();
HttpGet getRequest = new HttpGet(url);
getRequest.addHeader("accept", "application/json");
getRequest.addHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0");
getRequest.setConfig(requestConfig);
System.out.println("this is get request config : \n"+getRequest);
System.out.println("\n start execute");
HttpResponse response = httpClient.execute(getRequest);//it will stucked here and no reponses
System.out.println("\n end execute");
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
Please comment below if you have any idea or any advice and Appreciate your help.
This is not spoon feed, I have been researched for over 2 weeks.
Thanks
I have worked in such scenarios like yours when the written code needs to make any HTTP request to an API (third party).
As far as my experience says, there should be some issue of Authentication for your code.
As you said hitting the same API on browser also says "Access denied", some login credentials must be required by API with the GET request you are sending, so when creds are not found, API responds with "Access Denied"..
Could you check the http status code your getting in postman while you are hitting the API, it must be 401/403(Unauthorized).
if in postman http status code is 401/403 indeed, then Kindly ask your University Lecturer for any logins that might be required to hit the API.

How to send GET request with google OAuth2 and Java to script.google.com web page?

GET is working for me but I get google services authorization page when I send it. I read guides from google but still don't understand how to use Credentials right.
This thing is for managing script files itself and have nothing to do with my problem :/
Would be decent if it is possible in Java
After sign in google you will be redirected on redirect page with google code. Redirect page could be set in google private user console. When you will get google code you could use code for obtaining jwt with GoogleAuthorizationCodeFlow
for example
GoogleAuthorizationCodeTokenRequest googleAuthorizationCodeTokenRequest = codeFlow.newTokenRequest(code)
.setRedirectUri(redirectUrl);
try {
GoogleTokenResponse googleTokenResponse = googleAuthorizationCodeTokenRequest.execute();
} catch (IOException e) {
throw new ExternalAuthenticationException("Invalid google 'code' parameter (disposable)");
}

Azure Graph API 403 Error using Java tutorial

I’ve been working through a doc at:
https://learn.microsoft.com/en-us/azure/active-directory/active-directory-devquickstarts-webapp-java
But when I run the project, I’m redirected to the ADFS login page and after authentication im receiving this error:
java.io.IOException: Server returned HTTP response code: 403 for URL: https://graph.windows.net/swisherint.onmicrosoft.com/users?api-version=2013-04-05
I get this error when I run from local host. I also deployed the sample app to Azure and getting the same error.
I've added permissions to Graph API with read directory permissions in active directory > App Registrations > Required permissions. I also added Windows Azure Active Directory permissions (sign in and read user profile)
Is this a common error? Am I using the wrong version of the Graph API? I've tried several solutions from other questions but not working.
It appears that the Azure Graph API requires the URI connection type, instead of the HttpUrlConnection the java tutorial used. This works without the 403 error:
try{
// OAuth2 is required to access this API. For more information visit:
// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks
// Specify values for path parameters (shown as {...})
URIBuilder builder = new URIBuilder("https://graph.windows.net/swisherint.onmicrosoft.com/users");
// Specify values for the following required parameters
builder.setParameter("api-version", "1.6");
// Specify values for optional parameters, as needed
// builder.setParameter("$filter", "startswith(displayName,'A')");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
users = EntityUtils.toString(entity);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
Thanks for responding!
KB
According to the new offical document reference for AAD Graph API Get Users, it seems the api-version property in the code should be changed to 1.6. Please try it.
Meanwhile, there is an Error code reference list that you can find the description of the common error code 403 for AAD Graph API calling. And be checking whether your issue is belong to the one of the errors Authentication_Unauthorized, Authorization_RequestDenied & Directory_QuotaExceeded.
Any update, please feel free to let me know.

How to retrieve home timeline from twitter in the form of .xml or JSON using java?

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.

Categories