【问题标题】:Google Spreadsheets API (Java)谷歌电子表格 API (Java)
【发布时间】:2023-05-13 03:45:01
【问题描述】:

我想用一个简单的 Java 程序计算的数值更新电子表格。 它不是一个 Android 应用程序或任何东西,只是普通的 java。

问题是程序退出我说帐户无效。 但是提供的凭据是 100% 有效的 - 我将它们从 eclipse 中复制出来并将它们粘贴到 gmail 登录表单中 - 它们可以工作..

类(这是api教程中的基础类):

import com.google.gdata.client.spreadsheet.*;
import com.google.gdata.data.spreadsheet.*;
import com.google.gdata.util.*;

import java.io.IOException;
import java.net.*;

public class MySpreadsheetIntegration {
  public static void main(String[] args)
      throws AuthenticationException, MalformedURLException, IOException, ServiceException {

    String USERNAME = "abc@gmail.com";
    String PASSWORD = "123";

    SpreadsheetService service =
        new SpreadsheetService("MySpreadsheetIntegration-v1");
    service.setUserCredentials(USERNAME, PASSWORD);

    // TODO: See other portions of this guide for code to put here...
  }
}

堆栈跟踪:

Exception in thread "main" com.google.gdata.client.GoogleService$InvalidCredentialsException: Invalid credentials
at com.google.gdata.client.GoogleAuthTokenFactory.getAuthException(GoogleAuthTokenFactory.java:660)
at com.google.gdata.client.GoogleAuthTokenFactory.getAuthToken(GoogleAuthTokenFactory.java:560)
at com.google.gdata.client.GoogleAuthTokenFactory.setUserCredentials(GoogleAuthTokenFactory.java:397)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:364)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:319)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:303)
at MySpreadsheetIntegration.main(MySpreadsheetIntegration.java:17)

我想知道这甚至可以使用没有 android sdk 和其他东西的 api 吗?

【问题讨论】:

    标签: java google-sheets gdata


    【解决方案1】:

    Google 电子表格 API 使用 OAuth 作为其服务的授权协议(在本例中为 API)。阅读Authorizing Requests 部分,了解您的应用程序如何获得授权和访问 API。

    另外,请考虑一下来自 Google 的警告

    警告:强烈建议不要使用ClientLogin 作为授权机制。在使用此机制之前,请彻底 考虑使用带有存储刷新令牌的 OAuth 2.0 或 OAuth 1.0a 使用存储的访问令牌。

    【讨论】:

    • 谢谢,我现在的问题是没有java sn-p,只有.net
    • 如果你仔细阅读,代码的右上角有一个标签,上面写着“Java”。因此,您可以在 Java 和 .NET 之间切换。
    • 对不起,我是盲人,或者没有关于“执行 OAuth 2.0”主题的 Java
    • 嗯,代码很清楚,假设您可以将代码“粘贴”(因为没有更好的词)到 Java 并修复导入和各种编译错误.
    • 重构代码对我来说并不容易...... OAuth2Parameters - 类变成 com.google.gdata.client.authn.oauth.OAuthParameters ??设置 id、secret 和 uri 的正确属性是什么而 OAuthUtil 根本没有静态方法......我真的不明白为什么他们不给我们一个 java sn-p - 毕竟它是所有希望使用 gdata api 的 Android 应用程序..
    【解决方案2】:

    使用 Oauth 不是强制性的。但是为了使没有 Oauth 的身份验证能够正常工作,您必须在您的 google 帐户安全设置(上面用于尝试登录的帐户)中打开 lessSecureApps

    要打开lessSecureApps,请转到https://www.google.com/settings/security/lesssecureapps

    【讨论】: