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}
Related
I am trying to consume Google's Beacon Proximity api. i have followed following steps to integrate them:
1) Signed up on Google Api Console.
2) Created new Project.
3) enabled Beacon proximity api and Nearby Api.
4) Generated Api key from Credentials.
Afterwards i invoke the following api:
{
"advertisedId": {
"type": "EDDYSTONE",
"id": "ABEiM0RVZneImaq7zN3u/w=="
},
"status": "ACTIVE",
"placeId": "ChIJL_P_CXMEDTkRw0ZdG-0GVvw",
"latLng": {
"latitude": "71.6693771",
"longitude": "-22.1966037"
},
"indoorLevel": {
"name": "1"
},
"expectedStability": "STABLE",
"description": "An example beacon.",
"properties": {
"position": "entryway"
}
}
with the follwing url:
https://proximitybeacon.googleapis.com/v1beta1/beacons:register?key=xxxx(my_api_key)
but the response says:
{
"error": {
"code": 403,
"message": "Unauthorized.",
"status": "PERMISSION_DENIED"
}
}
what is it that i am missing..
I also tried to use Beacon tools app but after entering EID and all other credentials..the App crashes(on android), while it is not able to connect to my eddystone on Ios.
Found the Solution, API_KEY can be used only to Access already registered beacons and their Characteristics, while to Register and update we require ClientId and client Secret key and you can register it in OAuth2.0 Playground.
it worked for me ;)
You can Get a service token after creating an account service key on the google API Console. Then generate it with this code:
String token = null;
try{
GoogleCredential credential = GoogleCredential.fromStream(accesKey).createScoped
(Collections.singleton("https://www.googleapis.com/auth/userlocation.beacon.registry"));
credential.refreshToken();
token = credential.getAccessToken();
} catch (FileNotFoundException ex) {
Logger.getLogger(BeaconRegisterClass.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(BeaconRegisterClass.class.getName()).log(Level.SEVERE, null, ex);
}
Then put it on the header of your call:
key: Authorization value: Bearer (your token here)
set the body of this call as beacon.json
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.
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
I am tryng to use the Google IO 2013 code sample, specifically the SocialStreamFragment to display google plus post based on a hashtag search.
Steps done:
Integrated SocialStreamFragment.java class and associated clasees, etc, in my project.
In the Console API , I have enabled Google+ API for my project
In the Console API I generated a Simple API Access key for Android Apps, configuring my app's package and debug/prod keys as allowed app.
I copied the Simple Access Key as Config.API_KEY.
However the code below to get the Activities/Posts fails with IOException : 403, "Access Not Configured".
public List<Activity> loadInBackground() {
mIsLoading = true;
// Set up the HTTP transport and JSON factory
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new GsonFactory();
// Set up the main Google+ class
Plus plus = new Plus.Builder(httpTransport, jsonFactory, null)
.setApplicationName(NetUtils.getUserAgent(getContext()))
.setGoogleClientRequestInitializer(
new CommonGoogleClientRequestInitializer(Config.API_KEY))
.build();
ActivityFeed activities = null;
try {
activities = plus.activities().search(mSearchString)
.setPageToken(mNextPageToken)
.setOrderBy("recent")
.setMaxResults(MAX_RESULTS_PER_REQUEST)
.setFields(PLUS_RESULT_FIELDS)
.execute();
mHasError = false;
mNextPageToken = activities.getNextPageToken();
} catch (IOException e) {
e.printStackTrace();
mHasError = true;
mNextPageToken = null;The
}
return (activities != null) ? activities.getItems() : null;
}
What am I missing or doing wrong?
My project has also in API Console configured Client IDs for installed applications. Can this be a problem?
Have you got the Google+ API enabled in the API console?
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.