Get the Post Of User On Google Plus - java

I got a problem on getting the post of user on google plus. I only have the access token and refresh token of this user ( not the ID !), how could i get the post from google plus of this user ?, i do searching a lot, but none of them meets my circumstance. When the user provide his google plus Id on the front end side, the access token and refresh token were generated and stored in database, i, on the backend side, will use these tokens to retrieve the post of this user.
p/s: I use this library https://code.google.com/p/google-plus-java-api/ because it looks so simple, i don't want to use so complicated library just for getting the post, thanks you guy a lot
here is my code
import com.googlecode.googleplus.GooglePlusFactory;
import com.googlecode.googleplus.Plus;
import com.googlecode.googleplus.model.activity.ActivityCollection;
import com.googlecode.googleplus.model.activity.ActivityFeed;
public void getInfo(String accessToken, String refreshToken) {
GooglePlusFactory factory = new GooglePlusFactory(clientId, clientSecret);
Plus plus = factory.getApi(accessToken, refreshToken,null);
if (plus != null) {
ActivityFeed af = plus.getActivityOperations().list("me",ActivityCollection.PUBLIC);
String firstpost = af.getItems().get(0).getObject().getContent();
}
, i got 403 error when call this method, the error output was :
403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "usageLimits",
"message" : "Daily Limit Exceeded. Please sign up",
"reason" : "dailyLimitExceededUnreg",
"extendedHelp" : "https://code.google.com/apis/console"
} ],
"message" : "Daily Limit Exceeded. Please sign up"
}
Actually, i think the reason is not because daily limit exceeded, because i got that message at the first time i run, i also turn the google+ api, google+ domain api on google api console. I suppose the error come from using the "me" in the "list" method to retrieve the post. I still dont' have any idea how to fix this problem
Updated #1#:
I have change my code a lot, so here is exactly what i stuck at, i already get a new accessToken, and (when it is still not expired) , i run this code below:
GoogleCredential credential = new GoogleCredential.Builder()
.setJsonFactory(JSON_FACTORY)
.setTransport(TRANSPORT)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET).build().setAccessToken(newAccessToken);
// Create a new authorized API client.
Plus service = new Plus.Builder(TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
// Get a list of people that this user has shared with this app.
ActivityFeed feed = service.activities().list("me", "public").execute()
then i got this error:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Insufficient Permission",
"reason" : "insufficientPermissions"
} ],
"message" : "Insufficient Permission"
}

Using "me" as the ID for the list call should work correctly, and your code generally appears correct.
The error message suggests that your client is unregistered. I would check to make sure of the following:
Make sure you have created a Client ID and Secret (and don't post them here!) for your project and you're passing them to the GooglePlusFactory correctly.
Make sure this project has the Google+ API turned on.
Make sure that the access token you're providing for the user corresponds to them authenticating to this same project

I solved this problem, everything is fine except 1 thing, that's is the access token and refresh token was created by some scopes but not the scopes Plus.me, that why's i can't request a new access token by using this refresh token, and then i got the insufficient permission error 403. So when i get the new access and refresh token by using the approriated scope, i can query with keyword "me". Hope you guy don't stuck like me, it takes me nearly 2 days to figure it out

Related

Bad request (invalid value) when trying to retrieve in-app purchase info using the Java Google Play Developer API v3 with a valid purchase token

When using the Java Google Play Developer API (version 3), and requesting purchase information for a valid purchase token, I get the below exception. The API call returns a 400 Bad Request response with the following message.
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Invalid Value",
"reason" : "invalid"
} ],
"message" : "Invalid Value"
}
Unfortunately there is no further information. I do not know what value is invalid.
First, we have contacted Google support about this. Unfortunately we have been going back and forth with Google support for almost 2 months and they still haven't even indicated they correctly understand what our problem is. Every time they reply, they give us suggestions that have literally nothing to do with the Google Play Developer API, even after thoroughly explaining the problem multiple times. This is the most frustrating support experience I've had in 20 years. Google support is clearly not going to be of any help here.
Second, we have successfully linked our Google Play account and our back-end. All necessary configuration is complete and working. On our back-end we are getting notifications from Google Play whenever an Android in-app purchase is made, and these notifications include a purchase token. This took some substantial effort, but I am confident this is now all correct, our service account is configured correctly, and all permissions and such are good.
I am able to successfully call the API that returns a list of available in-app-purchase products. I get a full and correct listing of the products we have configured in Google Play for users to purchase in our app. In order to make this call, we must provide credentials, and I assume the server is validating these credentials when we make this call. Since I can successfully make this call, I am assuming the "Invalid Value" is not related to our credentials. We are using a Google-generated JSON file created for a specific service account (not using a p12 file).
I have searched StackOverflow, and the rest of the internet looking for information on this issue. I have found many pages indicating the same or similar problem, but using an older version of the Google Play Developer API, which apparently did things differently. The solutions offered do not seem to apply to the v3 API. I have been searching for many weeks and trying various solutions I've come across all with no success.
I have written a test app that I run on my local PC which works when I am requesting a listing of in-app products, but does not work when requesting the purchase details for a given purchase token. I have tried with many different purchase tokens. I read that the test tokens are not actually valid for use with this particular API, so I actually released to production a build of our app that I am able to make a real, actual purchase with. I have done this, been charged by Google, and our back-end has received real and valid purchase tokens from these purchases.
private static void testGooglePlayDevAPI_Purchase() throws Throwable {
final String productIdSku = "[the_product_sku]";
final String purchaseToken = "[a_valid_purchase_token]";
final String packageName = "[our_app_id]";
final File GOOGLE_PLAY_DEV_API_CREDENTIALS =
new File("path_to_file/google-api-credentials.json");
final FileInputStream credentials =
new FileInputStream(GOOGLE_PLAY_DEV_API_CREDENTIALS);
final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
final HttpTransport TRANSPORT =
GoogleNetHttpTransport.newTrustedTransport();
String scope = AndroidPublisherScopes.ANDROIDPUBLISHER;
GoogleCredential credential = GoogleCredential
.fromStream(credentials, TRANSPORT, JSON_FACTORY)
.createScoped(Arrays.asList(scope));
AndroidPublisher publisher = new AndroidPublisher
.Builder(TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(packageName)
.build();
try {
AndroidPublisher.Purchases purchases = publisher.purchases();
AndroidPublisher.Purchases.Products products = purchases.products();
AndroidPublisher.Purchases.Products.Get get =
products.get(packageName, productIdSku, purchaseToken);
ProductPurchase product = get.execute();
System.out.println(String.format(
"Product purchase data found [developerPayload=%s]",
product.getDeveloperPayload()));
} catch (Throwable t) {
System.out.println(ExceptionSupport.getExceptionDetails(t));
}
}
I expect the above code to give me a response with valid product purchase data (a valid ProductPurchase instance that I can interrogate and process). Instead, all I ever get here is a 400 Bad Request response indicating that SOME VALUE (I don't know which) is invalid. The actual response is:
com.google.api.client.googleapis.json.GoogleJsonResponseException:
400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Invalid Value",
"reason" : "invalid"
} ],
"message" : "Invalid Value"
}
UPDATE:
I've provided my own answer to this question below.
I'll provide my own answer here because we finally found a work-around. It turns out that something in the Java Google Play Developer API (v3) client library is not working correctly. I don't know what it is, but the documentation for that client library is terrible and Google provides NO examples of using it. However, it turns out that we can successfully use the HTTPS/JSON/OAuth2 API directly without going through the Java client. We have implemented our server-side solution using this approach and caching the OAuth2 tokens in memcache until they expire.
I double-checked and we were emailing back-and-forth with Google support for 2 months!!! They were of no assistance at all. I find this to be remarkable (in a bad way).

Google Custom Search API: Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup

The Google Custom Search API is denying my requests, saying I've exceeded the limit. Their limit is 100 requests/day but I've not made any successful requests yet, and I've only made a total of about 5 requests.
I'm creating a Java application to use the Google CustomSearch API to make searches using my CustomSearch API key.
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.customsearch.Customsearch;
import com.google.api.services.customsearch.model.Result;
public class SearchBuilder {
public SearchBuilder() {
search = new Customsearch.Builder(new NetHttpTransport(), new JacksonFactory(), null) .setApplicationName("MyApp").build();
}
public List<Result> search(String query) throws IOException {
return search(query,100);
}
}
I've tried refreshing the API key, ensuring its enabled on the API Console but still no luck.
Running this code with my API key results in the following exception:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "usageLimits",
"message" : "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
"reason" : "dailyLimitExceededUnreg",
"extendedHelp" : "https://code.google.com/apis/console"
} ],
"message" : "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}
But I don't think code is the problem, as both a normal GET request and the Java code return the same JSON message citing exceeding my limit.
It says continued use requires signup but I'm unsure what this means - I've already signed up for an API key.
The problem was my Java code, I think I wasn't adding the credentials correctly in my code. Turns out I was malforming my GET request too.
Running the edited Google example returns the expected JSON search results:
curl -l GET 'https://www.googleapis.com/customsearch/v1?key=MY_API_KEY&cx=017576662512468239146:omuauf_lfve&q=lectures'
A request doesn't have to be 'succesful' to be counted to the limit. In googles eyes it is 'succesful' since it was a request. You are just not handling the data correctly. Signing up probably refers to the fact that you have to put in some bank details so that they can charge you for all the next requests.
As for the problem you yourself are having, I can't really help without some more code.

Write to GoogleSheet via API with Java

I am trying to write a value to a cell with Google Sheet API with Java.
For reading I used guide from Java Quickstart which worked fine for me.
For writing to Google Sheet I use:
service.spreadsheets().values().update(spreadsheetId, "Sheet1!A4:H", response).execute();
This function outputs the following error while run:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Request had insufficient authentication scopes.",
"reason" : "forbidden"
} ],
"message" : "Request had insufficient authentication scopes.",
"status" : "PERMISSION_DENIED"
}
As a Authentication Scope I am using
private static final List<String> SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS);
Apparently there were several issues together:
Delete credentials that were stored at /Users/XXX/.credentials.
Change Scopes to SheetsScopes.SPREADSHEETS.
Google Sheet Share and Edit options at on Sheet itself.
Now it works!
Thank you guys for help
I was having the same issue. I resolved the problem that was in the scope.
I just changed
SheetsScopes.SPREADSHEETS.READONLY
To
SheetsScopes.SPREADSHEETS
And it works very well.
The Java API must be used in an interactive way, if you're running this on a server that can't pop up a web-browser (which will let you approve an OAuth dialog), then the authentication flow doesn't get proper credentials and won't work.
While running this, do you see a browser pop up to approve an OAuth dialog? If not, you're likely running in a headless session and will need some other means to get the user's credentials.
Try replacing "Sheet1!A4:H" with A4:H

How can I give full permissions to Google Drive REST API?

I'm trying to create an app that copies and deletes existing spreadsheets. I've set up the DriveQuickstart from https://developers.google.com/drive/v2/web/quickstart/java
The error that I'm getting now is saying that I do not have sufficient permissions to access that, even after I click the "Allow" button that comes up on my browser after I run the sample.
My code is exactly the same as on the quickstart link.
I'm getting this stacktrace:
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Insufficient Permission",
"reason" : "insufficientPermissions"
} ],
"message" : "Insufficient Permission"
}
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1056)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at DriveQuickstart.main(DriveQuickstart.java:110)
To build on adjuremods response, this is what worked for me:
1) Change this line:
private static final List<String> SCOPES =
Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY);
to:
private static final java.util.Collection<String> SCOPES =
DriveScopes.all();
2) Delete your existing stored credentials so that it will fetch them again, and reexecute your program:
rm ~/.credentials/drive-java-quickstart/StoredCredential
Note: you want an OAuth Client ID called client_secret.json file, not the client_id.json file (I think - that's what worked for me anyway).
Since you're using the exact code form the QuickStart, it may have something to do with the scope set, its currently set as DriveScopes.DRIVE_METADATA_READONLY, which if you check out its meaning in the Choose Auth Scopes page, it states
Allows read-only access to file metadata, but does not allow any access to read or download file content
You can look at the cited page to know what scope it is you'll exactly use. Its most likely going to be https://www.googleapis.com/auth/drive, so check out the DriveScopes class for the constant of the same nature.

Why are the new profile scopes breaking requests to Google Classroom API in my app?

I have an application set up to access the Google Classroom API. I have it authorized and can pull Course and Roster data. It's updated to use the V1 calls, but when I add in the Profile.Name and Profile.Email scopes, I get the following error:
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Unregistered request was blocked. Please sign up using Google Developers Console.",
"reason" : "forbidden"
} ],
"message" : "Unregistered request was blocked. Please sign up using Google Developers Console.",
"status" : "PERMISSION_DENIED"
}
The service account has been authorized in the admin console with all 4 relevant Classroom scopes. The Domain has also been confirmed as having the Classroom APIs enabled, if I attempt to use them through the OAuth playground it all works fine.
Any ideas as to why I'm getting the error only when I add in the profile scopes?
The issue was that we were required to fill in a second form for Google to authorize the domain, we'd only found the first one. After filling in the new form, it all started working.

Categories