Android: Google Data API - 401 Token Invalid Error - android

Well, I tried using Account Manager and I am getting "401 Token Invalid" error. What can be the reason.
Debug Log
Account name = xxxxxx#gmail.com
Token is : DQAAALIAAAAh-xxxxxxx
Starting Google DATA API loader-----------------
Inside Google Notebook loader-----------------
Setting Token : DQAAALIAAAAh-xxxxx
Url is : https://docs.google.com/feeds/default/private/full
Exception getting docs feed : 401 Token invalid
Done Google DATA API loader-----------------
Sample Code:
Log.d("Main","\tInside GoogleDATA API -----------------");
HttpTransport transport = new NetHttpTransport();
GoogleHeaders headers = new GoogleHeaders();
Log.d("Main","\tSetting Token : " + authToken);
headers.setGoogleLogin(authToken);
headers.gdataVersion="3.0";
transport.defaultHeaders = headers;
AtomParser parser = new AtomParser();
parser.namespaceDictionary = Namespace.DICTIONARY;
transport.addParser(parser);
try {
DocsUrl url = DocsUrl.forDefaultPrivateFull();
DocumentListFeed feed = DocumentListFeed.executeGet(transport,url);
List<DocumentListEntry> docs = feed.docs;
Log.d("Main","\tDocs count = " + docs.size());
for (Iterator iterator = docs.iterator(); iterator.hasNext();) {
DocumentListEntry documentListEntry = (DocumentListEntry) iterator
.next();
Log.d("Main","\t\tDocument title is : " + documentListEntry.title);
}
} catch (IOException e) {
Log.d("Main","Exception getting docs feed : " + e.getMessage());
//handleException(e);
}
Log.d("Main","\tDone GoogleDATA API -----------------");

you should see how it works on this website http://n01se.net/gmapez/start.html

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();
}

Android Amazon SNS Invalid Parameter

Code Returns Exception Invalid Paramters
I need to know what are the invalid params ?
Is Application ARN string value from where to get it or it is a static value .
when to send device if returned from GCM ?
CreatePlatformEndpointRequest cpeReq =
new CreatePlatformEndpointRequest();
cpeReq.setCustomUserData("");
cpeReq.setToken(this.mToken);
cpeReq.setPlatformApplicationArn(retrieveEndpointArn());
client.setRegion(Region.getRegion(Regions.DEFAULT_REGION));
CreatePlatformEndpointResult cpeRes = client
.createPlatformEndpoint(cpeReq);
endpointArn = cpeRes.getEndpointArn();
} catch (InvalidParameterException ipe) {
String message = ipe.getErrorMessage();
System.out.println("Exception message: " + message);
Pattern p = Pattern
.compile(".*Endpoint (arn:aws:sns[^ ]+) already exists " +
"with the same Token.*");
Matcher m = p.matcher(message);
if (m.matches()) {
// the endpoint already exists for this token, but with
// additional custom data that
// CreateEndpoint doesn't want to overwrite. Just use the
// existing endpoint.
endpointArn = m.group(1);
} else {
// rethrow exception, the input is actually bad
throw ipe;
}
}

Android oAuth Refresh Token returns null

I've been trying to figure this out for awhile now, cant seem to get with anything I've tried.
I cant seem to retrieve the refresh token, it would come out as blank.
public class oaUTH extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... unused) {
try {
JsonFactory jsonFactory = new JacksonFactory();
HttpTransport transport = new NetHttpTransport();
CredentialStore credentialStore = new SharedPreferencesCredentialStore(prefs);
AccessTokenResponse accessTokenResponse = credentialStore.read();
GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(accessTokenResponse.accessToken,
transport,
jsonFactory,
OAuth2ClientCredentials.CLIENT_ID,
OAuth2ClientCredentials.CLIENT_SECRET,
accessTokenResponse.refreshToken+"&access_type=offline");
final Latitude latitude = new Latitude(transport, accessProtectedResource, jsonFactory);
latitude.apiKey=OAuth2ClientCredentials.API_KEY;
Log.i("AGENTPORTAL", "Access Token = " + accessTokenResponse.accessToken + ", Expires in = " + accessTokenResponse.expiresIn + ", Refresh Token = " + accessTokenResponse.refreshToken + ", Scope = " + accessTokenResponse.scope);
LatitudeCurrentlocationResourceJson currentLocation = latitude.currentLocation.get().execute();
String locationAsString = convertLocationToString(currentLocation);
Log.i("TAG", locationAsString);
//textView.setText(locationAsString);
} catch (Exception ex) {
ex.printStackTrace();
//textView.setText("Error occured : " + ex.getMessage());
startActivity(new Intent().setClass(getApplicationContext(),OAuthAccessTokenActivity.class));
}
Here is the log: Access Token = **AHES6ZTeqgwdxjll6Gb4Cf9I0_n5bO_OdgR2OR**WLPCPzJ5xtO5M, Expires in = 3599, Refresh Token = , Scope =
Any idea where refresh token = " " ? I've added "&access_type=offline" but still no luck. Any help is deeply appreciated!
I just figured out how to get the refresh token, I'll tell you what I did just in case someone ever runs into the same problem...
String authorizationUrl = new GoogleAuthorizationRequestUrl(
OAuth2ClientCredentials.CLIENT_ID,
OAuth2ClientCredentials.REDIRECT_URI,
OAuth2ClientCredentials.SCOPE).build();
That piece of code is what is first called to start the whole authorization process. Whats missing in it is what several people here on SO had suggested, you need to include "access_type=offline&approval_prompt=force" in the URL link.
To make it work, I simply changed the authorizationUrl to
String authorizationUrl = "https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force&client_id=" + OAuth2ClientCredentials.CLIENT_ID + "&redirect_uri=" + OAuth2ClientCredentials.REDIRECT_URI + "&response_type=code&scope=" + OAuth2ClientCredentials.SCOPE

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.

Gdata map Api in android

i am trying to implement gdata map api in my android project.. but i am unable to solve this error
"java.lang.VerifyError: com.google.gdata.client.media.MediaService"
i am using all the libraries required to implement gdata apis
MapsService myService = new MapsService("createMap"); error is coming due to this line
is there any clue..
thnx..
i am trying with following code
//
**MapsService myService = new MapsService("createMap");**
try {
// Replace username and password with your authentication credentials
myService.setUserCredentials("username","password");
createMap(myService);
} catch(AuthenticationException e) {
System.out.println("Authentication Exception");
} catch(ServiceException e) {
System.out.println("Service Exception: " + e.getMessage());
} catch(IOException e) {
System.out.println("I/O Exception");
}
}
public static MapEntry createMap(MapsService myService)
throws ServiceException, IOException {
// Replace the following URL with your metafeed's POST (Edit) URL
// Replace userID with appropriate values for your map
final URL editUrl = new URL("http://maps.google.com/maps/feeds/maps/userID/full");
MapFeed resultFeed = myService.getFeed(editUrl, MapFeed.class);
URL mapUrl = new URL(resultFeed.getEntryPostLink().getHref());
// Create a MapEntry object
MapEntry myEntry = new MapEntry();
myEntry.setTitle(new PlainTextConstruct("Demo Map"));
myEntry.setSummary(new PlainTextConstruct("Summary"));
myEntry.getAuthors().add(new Person("My Name", null, "username"));
return myService.insert(mapUrl, myEntry);
}
You have to add "servlet.jar, activation.jar, mail.jar" In your source code

Categories

Resources