YouTube Data API v3 Authentification Error - android

I'm trying to access the YouTube Data API v3 from within my app to fetch some videos from a specific channnel. I created an API Key and inserted my package name and the SHA-1 fingerprint. However, it does not work.
This is the error:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "usageLimits",
"message" : "The Android package name and signing-certificate fingerprint, null and null, do not match the app restrictions configured on your API key. Please use the API Console to update your key restrictions.",
"reason" : "ipRefererBlocked",
"extendedHelp" : "https://console.developers.google.com/apis/credentials?project=1097633804344"
} ],
"message" : "The Android package name and signing-certificate fingerprint, null and null, do not match the app restrictions configured on your API key. Please use the API Console to update your key restrictions."
}
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:1065)
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 de.axelrindle.youtubeapitest.YoutubeConnector.fetchVideoIDS(YoutubeConnector.java:59)
at de.axelrindle.youtubeapitest.util.VideoIDFetcher.fetchVideoIDS(VideoIDFetcher.java:62)
at de.axelrindle.youtubeapitest.InitService.onHandleIntent(InitService.java:57)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.os.HandlerThread.run(HandlerThread.java:61)
And here is the code, which sends the request:
YoutubeConnector.class
public YoutubeConnector(Context context) {
this.context = context;
youTube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) throws IOException {}
}).setApplicationName("YouTube Data API v3 Test").build();
try {
query = youTube.search().list("id,snippet");
query.setKey(DevKey.YOUTUBE_API);
query.setType("video");
query.setFields("items(id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url)");
query.setChannelId("UC3ifTl5zKiCAhHIBQYcaTeg");
query.setMaxResults(maxResults);
} catch (IOException e) {
Log.e("YoutubeConnector", "Failed to connect to YouTube: " + e.getMessage());
}
}
public List<String> fetchVideoIDS() {
List<String> ids = new ArrayList<>();
maxResults += 10;
try {
SearchListResponse response = query.execute();
List<SearchResult> results = response.getItems();
for (SearchResult result : results) {
ids.add(result.getId().getVideoId());
}
} catch (IOException e) {
e.printStackTrace();
}
return ids;
}
Any help is MUCH appreciated!

Fixed it by myself.
I was just using the wrong API key.
EDIT:
Maybe I should mention that it worked when I used an browser api key instead of an android api key.

Related

Youtube data api error in signed apk?

I'm trying to implement the functionality of add subscription to youtube channel from android app.
i already done with :
register app on developer console. -Done
package name and SHA-1 certificate fingerprint. -Done
Image
Google account account authentication with "https://www.googleapis.com/auth/youtube" . -Done
Note : functionality is working fine in debug mode.
Issue: when i create a signed apk for publishing app on play store then subscribe button not working throw different errors each time .
i.e With unrestricted api key :
W/System.err: {
"c" : 0,
"errors" : [ {
"domain" : "global",
"reason" : "required",
"message" : "Required parameter: part",
"locationType" : "parameter",
"location" : "part"
} ],
"code" : 400,
"message" : "Required parameter: part"
}
Here is the code that Im doing
// Initialize credentials and service object.
mCredential = GoogleAccountCredential.usingOAuth2(getApplicationContext(), Arrays.asList(SCOPES)).setBackOff(new ExponentialBackOff());
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
YouTube mService = new YouTube.Builder(transport, jsonFactory, mCredential)
.setApplicationName(getResources().getString(R.string.app_name))
.setYouTubeRequestInitializer(new YouTubeRequestInitializer(Config.KEY))
.build();
channelId = myListModel.getYoutubeChannelId();
// Create a resourceId that identifies the channel ID.
ResourceId resourceId = new ResourceId();
resourceId.setChannelId(channelId);
resourceId.setKind("youtube#channel");
// Create a snippet that contains the resourceId.
SubscriptionSnippet snippet = new SubscriptionSnippet();
snippet.setResourceId(resourceId);
// Create a request to add the subscription and send the request.
// The request identifies subscription metadata to insert as well
// as information that the API server should return in its response.
Subscription subscription = new Subscription();
subscription.setSnippet(snippet);
YouTube.Subscriptions.Insert subscriptionInsert = mService.subscriptions().insert("snippet,contentDetails", subscription);
try {
Subscription returnedSubscription = subscriptionInsert.execute();
// Print information from the API response.
System.out.println("\n================== Returned Subscription ==================\n");
System.out.println(" - Id: " + returnedSubscription.getId());
System.out.println(" - Title: " + returnedSubscription.getSnippet().getTitle());
addSubscriber(myListModel);
} catch (UserRecoverableAuthIOException mLastError) {
startActivityForResult(mLastError.getIntent(), REQUEST_AUTHORIZATION);
}
} catch (GoogleJsonResponseException e) {
System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
e.printStackTrace();
} catch (Throwable t) {
System.err.println("Throwable: " + t.getMessage());
t.printStackTrace();
}

execute youtube playlists got GoogleJsonResponseException: 401 Unauthorized

I use android AccountManager to get authToken like this:
private void getGoogleAccountName(){
AccountManager.get(activity.getApplicationContext())
.getAuthTokenByFeatures("com.google", "oauth2:https://gdata.youtube.com", null, activity, null, null, this, null);
}
// I implement AccountManagerCallback<Bundle> in this class
#Override
public void run(AccountManagerFuture<Bundle> future) {
boolean hasAccount = checkGoogleAccount(future);
if (hasAccount) {
getYoutubeVideoByLib("");
}
}
private boolean checkGoogleAccount(AccountManagerFuture<Bundle> future){
try {
Bundle bundle = future.getResult();
accountName = bundle.getString(AccountManager.KEY_ACCOUNT_NAME);
authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
} catch (Exception e) {
return false;
}
return true;
}
then I use google apis with authToken trying to get user's playlists
private void getYoutubeVideoByLib(String pageToken){
YouTube youtube = new YouTube.Builder(
new NetHttpTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName(activity.getString(R.string.app_name)).build();
YouTube.Playlists.List query = null;
try{
query = youtube.playlists().list("snippet");
query.setOauthToken(authToken);
query.setKey("YOUTBE_API_KEY");
query.setMine(true);
if(!TextUtils.isEmpty(pageToken)) {
query.setPageToken(pageToken);
}
PlaylistListResponse response = query.execute();
...
} catch(IOException e) {
return;
}
}
but I found out some google account got GoogleJsonResponseException in query.execute();
com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
{
"code" : 401,
"errors" : [ {
"domain" : "global",
"location" : "Authorization",
"locationType" : "header",
"message" : "Invalid Credentials",
"reason" : "authError"
} ],
"message" : "Invalid Credentials"
}
the weird thing is that, some accounts work fine before but after these users got this exception, they can't get their playlists anymore.
Does anyone meet the same problem?
===================================================================
I solved it myself. I made a big mistake...
In google developer console, I set API KEY but not OAuth 2.0 client ID.
After setting both and change code below, it work fine now.
String[] SCOPES = {YouTubeScopes.YOUTUBE_READONLY};
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(getApplicationContext(), Arrays.asList(SCOPES));
credential.setSelectedAccountName(accountName);
YouTube youtube = new YouTube.Builder(transport, jsonFactory, credential).setApplicationName(getString(R.string.app_name)).build();

Life post Android Mobile Backend Starter? Authentication errors

I'm picking up a project from last year that was based on the now discontinued 'mobile backend starter' from Google. I believe the app was left in a working state but it now seems to fail the authentication when the "Secured by Client IDs" setting is selected on the web page google provided. I get the following error:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
{
"code": 401,
"errors": [
{
"domain": "global",
"location": "Authorization",
"locationType": "header",
"message": "Unauthenticated calls are not allowed",
"reason": "required"
}
],
"message": "Unauthenticated calls are not allowed"
}
The error results from running this method
private void listPosts(final String alertTxt) {
// create a response handler that will receive the result or an error
CloudCallbackHandler<List<CloudEntity>> handler =
new CloudCallbackHandler<List<CloudEntity>>() {
#Override
public void onComplete(List<CloudEntity> results) {
//mAnnounceTxt.setText(R.string.announce_success);
mAnnounceTxt.setText(alertTxt);
mPosts = results;
animateArrival();
updateGuestbookView();
}
#Override
public void onError(IOException exception) {
mAnnounceTxt.setText(R.string.announce_fail);
animateArrival();
handleEndpointException(exception);
}
};
...
I am not really sure where/how to start debugging this?
401 Errors are usually caused by any of the following:
Expired token
Token revocation
Token not authorized for needed scopes
Request not authorized correctly with OAuth
Try refreshToken() to resolve expired token issues

Android and Google Custom Search API

I'm trying find images with help google custom search api.
Everytime i'm getting error 403.
What i'm doing incorrect?
I registered project in google developer console, turned on Custom Search API and created Key for Android applications.
I have api-key and cx id
Code for getting search results:
String key = "AIzaSyBixxZ28popSAyP0YdlzvnWFECXktLQR4w";
String cx = "009034774129468977321:wl08kmocg3m";
String qry = "spring";// search key word
try {
HttpRequestInitializer httpRequestInitializer = new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) throws IOException {
}
};
JsonFactory jsonFactory = new JacksonFactory();
HttpTransport httpTransport = new NetHttpTransport();
Customsearch customsearch = new Customsearch.Builder(httpTransport, jsonFactory, httpRequestInitializer)
.setApplicationName("CTTProject")
.build();
Customsearch.Cse.List list = customsearch.cse().list(qry);
list.setKey(key);
list.setCx(cx);
Search results = list.execute();
List<Result> items = results.getItems();
for (Result item : items) {
Log.d("Response", item.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
everytime I'm getting result:
886-895/gsihome.reyst.ctt W/System.err﹕ com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
886-895/gsihome.reyst.ctt W/System.err﹕ {
886-895/gsihome.reyst.ctt W/System.err﹕ "code" : 403,
886-895/gsihome.reyst.ctt W/System.err﹕ "errors" : [ {
886-895/gsihome.reyst.ctt W/System.err﹕ "domain" : "usageLimits",
886-895/gsihome.reyst.ctt W/System.err﹕ "message" : "Access Not Configured. The API is not enabled for your project, or there is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your configuration.",
886-895/gsihome.reyst.ctt W/System.err﹕ "reason" : "accessNotConfigured",
886-895/gsihome.reyst.ctt W/System.err﹕ "extendedHelp" : "https://console.developers.google.com"
886-895/gsihome.reyst.ctt W/System.err﹕ } ],
886-895/gsihome.reyst.ctt W/System.err﹕ "message" : "Access Not Configured. The API is not enabled for your project, or there is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your configuration."
886-895/gsihome.reyst.ctt W/System.err﹕ }
Although a very late answer but it maybe helpful for others.
This problem happens because you are using the wrong key in making the request.
Instead of "Android Key" you have to create a "Browser Key" and use it for making the request.You can create Browser Key from Credentials section in the Google API console.
Example
https://www.googleapis.com/customsearch/v1?q=a&key={BROWSER__KEY}&cx={SEARCH_ENGINE_KEY}

Google drive SDK 2.0 throws error 400 Bad Request

I've been fighting with Google Drive API for Android for more than 50 hours now, and have not come one inch closer. From my understanding, there are 1001 ways to access Google drive (Google Docs API, REST & Google Drive SDK v2). I'm using Google Drive SDK v2. I want want to access Google Drive to upload jpeg files. Platform, Android 2.2+.
What I've tried:
Using the recently released SDK:
http://code.google.com/p/google-api-java-client/wiki/APIs#Drive_API
I've watched the Google I/O sesssion, but the most important part (how to create a Drive object using your Client ID & Client Secret) was left out:
https://developers.google.com/events/io/sessions/gooio2012/705/
I have created multiple keys on https://code.google.com/apis/console. The last one I've created (and tested with) was created using "Create another client ID..." -> "Installed Application" -> "Android". I've used the key in the ~/.android/debug.keystore.
I've also tried to create a key for an "Other" (instead of Android/iOS) installed app, but this gives me a Client ID and Client secret. It seems like the Drive object does not accept a client secret.
Where the code says "1234567890-abcdefghij123klmnop.apps.googleusercontent.com", I've tried to use both "API key" and the "Client ID", both gave the same error.
My code:
Account account = AccountManager.get(context).getAccountsByType(
"com.google")[0];
String token;
try {
token = GoogleAuthUtil.getToken(context, account.name, "oauth2:"
+ DriveScopes.DRIVE_FILE);
} catch (UserRecoverableAuthException e) {
context.startActivityForResult(e.getIntent(), ASK_PERMISSION);
return;
} catch (IOException e) {
return;
} catch (GoogleAuthException e) {
return;
}
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
final String tokenCopy = token;
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
public void initialize(JsonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest
.setKey("1234567890-abcdefghij123klmnop.apps.googleusercontent.com");
driveRequest.setOauthToken(tokenCopy);
}
});
final Drive drive = b.build();
FileList files;
try {
files = drive.files().list().setQ("mimeType=text/plain").execute();
} catch (IOException e) {
e.printStackTrace(); // throws HTTP 400
}
The error I'm getting is:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"location" : "q",
"locationType" : "parameter",
"message" : "Invalid Value",
"reason" : "invalid"
} ],
"message" : "Invalid Value"
}
As the error message suggests, your error is in the query parameter q. The correct syntax for your q parameter is
files = drive.files().list().setQ("mimeType='text/plain'").execute();
and not :
files = drive.files().list().setQ("mimeType=text/plain").execute();
Looking at your code, you are fully authenticated and your request is failing because of this syntax error.

Categories

Resources