How to properly integrate Pinterest in Android app? - android

I am using the REST API for integrating Pinterest into my Android app, but I'm getting an error when attempting to access categories.
My code:
String url = "https://api.pinterest.com/";
String allCategories = "/v2/boards/categories/";
RestClient client = new RestClient(url + allCategories);
String response = "";
try {
client.AddParam("limit", "36");
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
response = client.getResponse();
} catch (Exception e) {
System.out.println(">>> Exception >>> " + e + " >>> Message >>> "
+ e.getMessage());
}
System.out.println(">>> response >>> " + response);
Log.d(">> Login response >>> ", response);
I'm getting the following error returned from the endpoint:
{
"message": "Please upgrade your app!",
"error": "Authentication failed: Please upgrade your app!"
}

Pinterest doesn't have any official api, and it's unofficial api is not working now. So I don't think your code will work any way, unless someone finds any other unofficial api or Pinterest releases the official version.
PS: More Info.

As of today, pinterest API has been taken down
(look here)
In the meantime you might want to use this 3rd party implemented scraper, which works just like an API
http://pinterestapi.co.uk/
You can use this to get the boards, likes and pins of a user.
Note: Curiously the count for the v1 api still works. But again this is undocumented behaviour and dont rely on this

Related

Error 200 (job canceled) when streaming data from Android to BigQuery

I've been trying to build some functionality into my app too allow user-generated data (EEG recordings) to be sent to a central BigQuery database.
I've never done any networking code in Java before, so I shied away from doing the POST or REST-based strategies recommended here. The BigQuery Java client library seemed to be exactly what I needed, though I was completely confused why it wouldn't officially support Android.
Still, I came across this example Android app (from Google no less) that promised to do exactly what I wanted with the BigQuery Client library. I incorporated it into my app as follows:
// .... in an AsyncTask
#Override
protected String doInBackground(String... params) {
String CSV_CONTENT = params[0];
try {
AssetManager am = MainApplication.getInstance().getAssets();
InputStream isCredentialsFile = am.open(CREDENTIALS_FILE);
BigQuery bigquery = BigQueryOptions.builder()
.authCredentials(AuthCredentials.createForJson(isCredentialsFile))
.projectId( PROJECT_ID )
.build().service();
TableId tableId = TableId.of(DATASET,TABLE);
Table table = bigquery.getTable(tableId);
int num = 0;
Log.d("Main", "Sending CSV: ");
WriteChannelConfiguration configuration = WriteChannelConfiguration.builder(tableId)
.formatOptions(FormatOptions.csv())
.build();
try (WriteChannel channel = bigquery.writer(configuration)) {
num = channel.write(ByteBuffer.wrap(CSV_CONTENT.getBytes(StandardCharsets.UTF_8)));
} catch (Exception e) {
Log.d("Main", e.toString());
}
Log.d("Main", "Loading " + Integer.toString(num) + " bytes into table " + tableId);
} catch (Exception e) {
Log.d("Main", "Exception: " + e.toString());
}
return "Done";
}
This runs without any errors and fires off an API call that is detected by Google Cloud Storage. However, it returns error 200 (job was cancelled) every time. I don't understand how this could be since I'm not doing anything in the code to cancel the request and I don't see how the async task I put the call in could be cancelled.
Was this just a bad example app I copied and a bad usage of the BigQuery Client? If so, what's the best way to send data to BigQuery from Android?

Getting Google+ Friends Android (HTTP Request)

I am developing an app where users can log in with Google+. I added the Google+ sign in button and the user can log in without any issues.
Where I am having trouble is in retrieving the friends/ people in circles. This feature is not in the Android API, so I am trying to achieve this with an HTTP request (as documented here)
I set up my application in the developer console with a Public API access Android Key.
When I use an HttpGet with this URL:
https://www.googleapis.com/plus/v1/people/{the user's g+ id}/people/visible?key={my API key from the console}
I get a "keyInvalid" error with a "Bad Request" message.
If I try it without "?key={my key}" I get a "dailyLimitExceedingUnreg" error with message "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
Do you know why my reqest isn't working? What can I do to get it to work?
Okay, it turns out I didn't need to use HTTP get. Thanks for your responses.
This code did the trick:
Plus.PeopleApi.loadVisible(mGoogleApiClient,null).setResultCallback(new ResultCallback<People.LoadPeopleResult>() {
#Override
public void onResult(People.LoadPeopleResult loadPeopleResult) {
if (loadPeopleResult.getStatus().getStatusCode() == CommonStatusCodes.SUCCESS) {
PersonBuffer personBuffer = loadPeopleResult.getPersonBuffer();
try {
int count = personBuffer.getCount();
for (int i = 0; i < count; i++) {
Log.d(TAG, "Person " + i + " name: " + personBuffer.get(i).getDisplayName()+ " - id: " + personBuffer.get(i).getId());
}
} finally {
personBuffer.close();
}
} else {
Log.e(TAG, "Error");
}
}
});
You need to log in to http://console.developers.google.com and get an API key, the instead of ?key= you should put ?key=RANDOMCHARACTERS replacing RANDOMCHARACTERS for the key you got from Google.
If you haven't created a project, first you'll need to create one in that website, after that you should see the list of available API, search for the Google+ API and enable it to get the corresponding key.
People.list is an API method that requires user authentication not application authentication. Basically the only way you can make the request is like this:
GET https://www.googleapis.com/plus/v1/people/me/people/visible?access_token={user access_token}

How to search videos with youtube data API in Android

I'm developing an application in Android which needs to search for videos of YouTube by Keyword. I have used Youtube data API with the code below:
try {
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("YoutubeQoE").build();
// Define the API request for retrieving search results.
YouTube.Search.List search = youtube.search().list("id,snippet");
// Set your developer key from the Google Cloud Console for
// non-authenticated requests. See:
// https://cloud.google.com/console
search.setKey(DeveloperKey.DEVELOPER_KEY);
search.setQ("dogs");
// Restrict the search results to only include videos. See:
// https://developers.google.com/youtube/v3/docs/search/list#type
search.setType("video");
// To increase efficiency, only retrieve the fields that the
// application uses.
//search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
search.setMaxResults(25);
SearchListResponse searchResponse = search.execute();
List<SearchResult> lista = searchResponse.getItems();
} catch (GoogleJsonResponseException e) {
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (IOException e) {
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
For de DEVELOPER_KEY I have used a public API access at google developer console.
But when I execute the program there is a problem in the line:
SearchListResponse searchResponse = search.execute();
In the android manifest.xml I have these permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
I would be very grateful if anybody could help me
Another way of achieving this would be getting results from this:
https://www.googleapis.com/youtube/v3/search?part=snippet&q=eminem&type=video&key=<key>
You can play with parameters to get what you actually need. You also need an API key from https://console.developers.google.com/.
You can compare your project against YouTube Direct Lite for Android. Yes, instead of OAuth2, setting API key would be enough.
Generally, this error occurs when someone tries to perform network calls on UI Thread, which is not allowed in Android.
check logcat if you get this error - (error-android-os-networkonmainthreadexception)
Go through this answer for the solution to this problem - fix of neworkonmainthreadexception

Send scores to facebook graph api from android app

I want to post score points using facebook graph api, from my android application
I create android app in facebook developers page. I set to Native Android App , and I set Mobile Web settings like on image below
In android code I user this permissions for my app:
String[] permissions = {"publish_stream","publish_actions","user_games_activity","friends_games_activity"};
After successful login on facebook, I try to post score points to facebook using this android code
Bundle params = new Bundle();
params.putString("score", "100");
//params.putString("access_token", "token as constant");
String response = "null";
Utility.mFacebook.setAccessToken("token as constant");
try {
response = Utility.mFacebook.request("user_id/scores", params, "POST");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
And I receive this response:
{"error":{"message":"(#15) This method must be called with an app access_token.","type":"OAuthException","code":15}}
I get same error if I use Graph API Explorer:
In facebook settings ->Apps -> AppName -> Advanced->App Type is set to "Web" (I also try with Native/Desktop but I get same error)
Can anyone help me and tell me how to sent score from my android app to fb?
Thanks
"(#15) This method must be called with an app access_token."
Looks like you tried with an user access token.
See https://developers.facebook.com/docs/authentication/applications/ on how to get an app access token.

Android - unable to use OAuth access token to retrieve Google Reader feeds

I need to obtain OAuth2 authentication token to pass it to the server so it can fetch list of Google Reader feeds for the user. Server is .NET - I have no access to it or to it's code but most likely it is using unofficial Reader API
I was able to use Android Account manager to obtain valid token for this purpose with the following code (notice that authTokenType="reader")
Account account = accounts[0];
manager.getAuthToken(account, "reader", null, this, new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> future) {
try {
// If the user has authorized your application to use the tasks API
// a token is available.
String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
// Now you can send the token to API...
cacheManager.putString(GOOGLE_AUTH, token);
GoogleReaderManager.startAddFeedActivity(AddGoogleReaderSourcesActivity.this);
finish();
} catch (OperationCanceledException e) {
Log.e(TAG, "User cancelled", e);
finish();
} catch (Exception e) {
Log.e(TAG, "Failed to obtain Google reader API_KEY", e);
}
}
}, null);
The code above works fine when I send token to the server side .Net app: the app is able to retrieve the list of Reader feeds.
The problem is that this only works for "Google inside" devices. On Nook I have no such luck since there's no way that I was able to find to add Google account to the account manager. So I'm trying to it using OAuth 2 protocol as described here
It works fine as far as obtaining the token: User approves the app from the mobile page which returns the code token which then mobile app exchanges for the Auth token. However this token will not work with the server process. I have a feeling that perhaps I'm using the wrong scope in this URL:
https://accounts.google.com/o/oauth2/auth?response_type=code&scope=https://www.google.com/reader/api/0/subscription/list&redirect_uri=http://localhost&approval_prompt=force&state=/ok&client_id={apps.client.id}
Scopes that I did try in various combinations:
https://www.google.com/reader/api
https://www.google.com/reader/api/0
https://www.google.com/reader/api/0/subscription/list
https://www.google.com/reader/api+https://www.google.com/reader/atom
Here's example of JSON that is returned from get token POST
{"expires_in":3600,
"token_type":"Bearer",
"access_token":"ya29.AHES6ZSEvuUb6Bvd2DNoMnnN_UnfxirZmf_RQjn7LptFLfI",
"refresh_token":"1\/bUwa5MyOtP6VyWqaIEKgfPh08LNdawJ5Qxz6-qZrHg0"}
Am I messing up scope or token type? Not sure how to change a token type. Any other ideas?
P.S. Google account login page asks: Manage your data in Google Reader, that's why I suspect that the scope is wrong
I got it working for https://www.google.com/reader/api/0/subscription/list. So thought of sharing with you.
I have valid access_token:
This is what i tried to resolve it (partially) :
Google provides OAuth 2.o playgound; where they actually simulate all aspects of OAuth 2.0 as well as final API call to fetch data.
I found this very helpful as it clearly shows what is being sent to request.
Here is the URL : https://developers.google.com/oauthplayground/
Using this, i tweaked my api call below and it works :)
public static String getReaderContent(String accessToken){
String url = "https://www.google.com/reader/api/0/subscription/list" ;
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(url);
String response="";
method.setRequestHeader("Authorization", "OAuth "+accessToken);
try {
int statusCode = client.executeMethod(method);
String response= method.getResponseBodyAsString();
System.out.println("response " + responseStr);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
So this works properly fine for getting subscription list; but have not been able to make it work for reader api which you have mentioned in your question.
Let me know if you have got way around google reader API.

Categories

Resources