简体   繁体   English

使用Google登录访问Android上的Google电子表格(或其他Google应用)

[英]Using Google sign in to access Google spreadsheets (or other Google apps) on Android

I'm developing an Android app and added a google sign in feature by following the tutorial here: https://developers.google.com/identity/sign-in/android/sign-in 我正在开发一款Android应用,并按照以下教程添加了Google登录功能: https//developers.google.com/identity/sign-in/android/sign-in

Now that the user is logged in I want to be able to read and write to their Google Spreadsheets. 现在用户已登录,我希望能够读取和写入他们的Google Spreadsheets。 I have looked at the spreadsheets API and tells you to use OAuth to authorize requests: https://developers.google.com/google-apps/spreadsheets/?hl=en 我查看了电子表格API并告诉您使用OAuth授权请求: https//developers.google.com/google-apps/spreadsheets/?hl = zh- CN

From the sign in page tutorial: 从登录页面教程:

The Google Sign-In button authenticates the user and manages the OAuth 2.0 flow, which simplifies your integration with the Google APIs. Google登录按钮可对用户进行身份验证并管理OAuth 2.0流程,从而简化您与Google API的集成。

I'm trying to use the Google sign in page for the authorization process. 我正在尝试使用Google登录页面进行授权。 I can successfully log in and out of my Google account now using the GoogleApiClient, so I tried adding the following code to access my spreadsheets which I call when the user is signed in: 我现在可以使用GoogleApiClient成功登录和退出我的Google帐户,因此我尝试添加以下代码来访问我在用户登录时调用的电子表格:

private class RetrieveFeedTask extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... urls) {
            SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");

            try {
                URL SPREADSHEET_FEED_URL = new URL(urls[0]);
                SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
                List<SpreadsheetEntry> spreadsheets = feed.getEntries();

                for (SpreadsheetEntry spreadsheet : spreadsheets) {
                    System.out.println(spreadsheet.getTitle().getPlainText());
                }

            } catch (ServiceException | IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

I call it using this line: 我用这行称呼它:

new RetrieveFeedTask().execute("https://spreadsheets.google.com/feeds/spreadsheets/private/full");

But on the service.getFeed call I'm getting the following error: 但是在service.getFeed调用上我收到以下错误:

com.google.gdata.util.ParseException: Unrecognized content type:application/binary
    at com.google.gdata.client.Service.parseResponseData(Service.java:2136)
    at com.google.gdata.client.Service.parseResponseData(Service.java:2098)
    at com.google.gdata.client.Service.getFeed(Service.java:1136)
    at com.google.gdata.client.Service.getFeed(Service.java:998)
    at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:645)
    at com.google.gdata.client.Service.getFeed(Service.java:1017)
    at com.zarwanhashem.ideatrackr.MainActivity$RetrieveFeedTask.doInBackground(MainActivity.java:320)
    at com.zarwanhashem.ideatrackr.MainActivity$RetrieveFeedTask.doInBackground(MainActivity.java:312)
    at android.os.AsyncTask$2.call(AsyncTask.java:292)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)

The solutions I found by looking at past questions did not work. 我通过查看过去的问题找到的解决方案不起作用。 One of them was to do service.setUserCredentials(user, password) before the call, but I don't know how to get that information as I didn't personally implement the OAuth part. 其中一个是在调用之前做service.setUserCredentials(用户,密码),但我不知道如何获取该信息,因为我没有亲自实现OAuth部分。

How can I resolve this error and use the google sign in page as my authentication? 如何解决此错误并使用google登录页面作为我的身份验证?


First, I'd suggest to set the authorization header containing the access token. 首先,我建议设置包含访问令牌的授权标头。

String accountname = Plus.AccountApi.getAccountName(mGoogleApiClient);
String scope = "oauth2:" + Scopes.PLUS_LOGIN + " " + "https://spreadsheets.google.com/feeds"; // add more scopes here
String accessToken = GoogleAuthUtil.getToken(context, accountname, scope);
service.setHeader("Authorization", "Bearer " + accessToken);

Also, please note that if you want to create new sheets you will need more scopes added: 此外,请注意,如果要创建新工作表,则需要添加更多范围:

Additionally, if an application needs to create spreadsheets, or otherwise manipulate their metadata, then the application must also request a Google Drive API scope; 此外,如果应用程序需要创建电子表格或以其他方式操纵其元数据,则应用程序还必须请求Google Drive API范围; see Choose Auth Scopes in the Google Drive API docs for information about the available scopes. 有关可用范围的信息,请参阅Google Drive API文档中的选择身份验证范围。

Another thing to try is to use the setOAuth2Credentials method, as described below, shamelessly stolen from Create Spreadsheet using Google Spreadsheet API in Google drive in Java . 另一件事是使用setOAuth2Credentials方法,如下所述, 使用Google Spreadsheet API在Java驱动器中使用Google Spreadsheet API无耻地窃取。

   HttpTransport httpTransport = new NetHttpTransport();
   JacksonFactory jsonFactory = new JacksonFactory();
   String [] scopesArray= {"https://spreadsheets.google.com/feeds", "https://docs.google.com/feeds"}; // add more scopes here
   final List SCOPES = Arrays.asList(scopesArray);
   GoogleCredential credential = new GoogleCredential.Builder()
     .setTransport(httpTransport)
     .setJsonFactory(jsonFactory)
     .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
     .setServiceAccountScopes(SCOPES)
     .setServiceAccountPrivateKeyFromP12File(SERVICE_ACCOUNT_PKCS12_FILE)
     .build();

   SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");
   service.setOAuth2Credentials(credential);

Regarding the P12 key file, see https://webapps.stackexchange.com/questions/58411/how-where-to-obtain-a-p12-key-file-from-the-google-developers-console 关于P12密钥文件,请参阅https://webapps.stackexchange.com/questions/58411/how-where-to-obtain-a-p12-key-file-from-the-google-developers-console

Other references: https://developers.google.com/google-apps/spreadsheets/authorize https://developers.google.com/drive/web/scopes https://developers.google.com/android/reference/com/google/android/gms/common/api/Scope 其他参考: https//developers.google.com/google-apps/spreadsheets/authorize https://developers.google.com/drive/web/scopes https://developers.google.com/android/reference/com /谷歌/机器人/克/普通/ API /范围

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM