将 OAuth 2.0 和 Google Spreadsheet API 与 Java 结合使用的示例是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21440101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:44:19  来源:igfitidea点击:

What is an example of using OAuth 2.0 and Google Spreadsheet API with Java?

javaoauthgoogle-spreadsheet-apigoogle-api-java-clientgoogle-sheets-api

提问by user2952212

Where is example code showing how to use the Google Data Java Client Libraryand its support for OAuth 2.0with the Google Spreadsheet API(now called the Google Sheets API)?

凡示例代码展示了如何使用Google Data Java Client Library其支持OAuth 2.0Google Spreadsheet API(现称Google Sheets API)?

回答by ErstwhileIII

Answer moved from original question to match site "Q and A" format.

答案从原始问题转移到匹配站点“问答”格式。

The Google Data Java Client Librarysupports OAuth 2.0. Unfortunately, there are no complete samples in the library showing how to use it with the Google Spreadsheet API.

Google Data Java Client Library支持OAuth 2.0。不幸的是,库中没有完整的示例展示如何将它与Google Spreadsheet API.

Here is an example that has worked for me. I hope someone find it helpful.

这是一个对我有用的例子。我希望有人觉得它有帮助。

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.Hymanson.HymansonFactory;
import com.google.gdata.util.ServiceException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

public class NewClass {

  // Retrieve the CLIENT_ID and CLIENT_SECRET from an APIs Console project:
  //     https://code.google.com/apis/console
  static String CLIENT_ID = "your-client-id";
  static String CLIENT_SECRET = "your-client-secret";
  // Change the REDIRECT_URI value to your registered redirect URI for web
  // applications.
  static String REDIRECT_URI = "the-redirect-uri";
  // Add other requested scopes.
  static List<String> SCOPES = Arrays.asList("https://spreadsheets.google.com/feeds");


public static void main (String args[]) throws IOException, ServiceException, com.google.protobuf.ServiceException{
    Credential credencial = getCredentials();
    JavaApplication20.printDocuments(credencial);
}


  /**
   * Retrieve OAuth 2.0 credentials.
   * 
   * @return OAuth 2.0 Credential instance.
   */
  static Credential getCredentials() throws IOException {
    HttpTransport transport = new NetHttpTransport();
    HymansonFactory jsonFactory = new HymansonFactory();

    // Step 1: Authorize -->
    String authorizationUrl =
        new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URI, SCOPES).build();

    // Point or redirect your user to the authorizationUrl.
    System.out.println("Go to the following link in your browser:");
    System.out.println(authorizationUrl);

    // Read the authorization code from the standard input stream.
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("What is the authorization code?");
    String code = in.readLine();
    // End of Step 1 <--

    // Step 2: Exchange -->
    GoogleTokenResponse response =
        new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
            code, REDIRECT_URI).execute();
    // End of Step 2 <--

    // Build a new GoogleCredential instance and return it.
    return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET)
        .setJsonFactory(jsonFactory).setTransport(transport).build()
     .setAccessToken(response.getAccessToken()).setRefreshToken(response.getRefreshToken());
  }

  // …
}

Here the other Class:

这是另一个类:

import com.google.api.client.auth.oauth2.Credential;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.docs.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.CellEntry;
import com.google.gdata.data.spreadsheet.CellFeed;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.data.spreadsheet.WorksheetEntry;
import com.google.gdata.data.spreadsheet.WorksheetFeed;
import com.google.gdata.util.ServiceException;
// ...
import java.io.IOException;
import java.net.URL;
import java.util.List;
// ...

public class JavaApplication20 {
  // …

  static void printDocuments(Credential credential) throws IOException, ServiceException {
    // Instantiate and authorize a new SpreadsheetService object.

     SpreadsheetService service =
            new SpreadsheetService("Aplication-name");
     service.setOAuth2Credentials(credential);
    // Send a request to the Documents List API to retrieve document entries.
    URL SPREADSHEET_FEED_URL = new URL(
        "https://spreadsheets.google.com/feeds/spreadsheets/private/full");
    // Make a request to the API and get all spreadsheets.
    SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL,
        SpreadsheetFeed.class);
    List<com.google.gdata.data.spreadsheet.SpreadsheetEntry> spreadsheets = feed.getEntries();
     if (spreadsheets.isEmpty()) {
      // TODO: There were no spreadsheets, act accordingly.
    }
com.google.gdata.data.spreadsheet.SpreadsheetEntry spreadsheet = spreadsheets.get(0);
    System.out.println(spreadsheet.getTitle().getPlainText());
// Get the first worksheet of the first spreadsheet.
    // TODO: Choose a worksheet more intelligently based on your
    // app's needs.
    WorksheetFeed worksheetFeed = service.getFeed(
        spreadsheet.getWorksheetFeedUrl(), WorksheetFeed.class);
    List<WorksheetEntry> worksheets = worksheetFeed.getEntries();
    WorksheetEntry worksheet = worksheets.get(0);

    // Fetch the cell feed of the worksheet.
    URL cellFeedUrl = worksheet.getCellFeedUrl();
    CellFeed cellFeed = service.getFeed(cellFeedUrl, CellFeed.class);

    // Iterate through each cell, printing its value.
    for (CellEntry cell : cellFeed.getEntries()) {
      // Print the cell's address in A1 notation
      System.out.print(cell.getTitle().getPlainText() + "\t");
      // Print the cell's address in R1C1 notation
      System.out.print(cell.getId().substring(cell.getId().lastIndexOf('/') + 1) + "\t");
      // Print the cell's formula or text value
      System.out.print(cell.getCell().getInputValue() + "\t");
      // Print the cell's calculated value if the cell's value is numeric
      // Prints empty string if cell's value is not numeric
      System.out.print(cell.getCell().getNumericValue() + "\t");
      // Print the cell's displayed value (useful if the cell has a formula)
      System.out.println(cell.getCell().getValue() + "\t");
    }

  }

  // ...
}

回答by Alex

You can find a step by step explanation with examples here. As a result, your code might look like this:

您可以在此处找到带有示例的分步说明。因此,您的代码可能如下所示:

SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");
service.setProtocolVersion(SpreadsheetService.Versions.V1); // It's important to specify the version

service.setRequestFactory(makeAuthorization());

SpreadsheetQuery q = new SpreadsheetQuery(new URL(DEFAULT_SPREADSHEET_QUERY));

SpreadsheetFeed feed;
try {
  feed = service.query(q, SpreadsheetFeed.class);
}
catch (AuthenticationException e) {
  refreshAccessToken(service);

  feed = service.query(q, SpreadsheetFeed.class);
}

SpreadsheetEntry spreadsheet = findSpreadSheet(feed);

...

// do your stuff

...

// a couple of utility methods are used above:

private void refreshAccessToken(SpreadsheetService service) throws Exception {
  String accessToken = callGetAccessTokenApi();

  // save access token

  service.getRequestFactory().setAuthToken(new GoogleAuthTokenFactory.OAuth2Token(new GoogleCredential().setAccessToken(accessToken)));
}

//private static final String GOOGLE_API_HOST = "https://www.googleapis.com/";

private String callGetAccessTokenApi() throws Exception {
  HttpClient client = HttpClients.createDefault();

  String url = String.format(
    "%soauth2/v3/token?client_id=%s&client_secret=%s&refresh_token=%s&grant_type=refresh_token",
    GOOGLE_API_HOST,
    googleAuthorization.getClientId(),
    googleAuthorization.getClientSecret(),
    googleAuthorization.getRefreshToken()
  );
  HttpPost post = new HttpPost(url);
  post.addHeader(ACCEPT_HEADER_NAME, "application/x-www-form-urlencoded");

  try {
    HttpResponse response = client.execute(post);

    JSONObject object = readJson(response);

    return object.getString("access_token");
  }
  finally {
    post.releaseConnection();
  }
}

private Service.GDataRequestFactory makeAuthorization() {
  Service.GDataRequestFactory requestFactory = new HttpGDataRequest.Factory();

  // load access token

  requestFactory.setAuthToken(new GoogleAuthTokenFactory.OAuth2Token(new GoogleCredential().setAccessToken(accessToken)));

  return requestFactory;
}

回答by wescpy

(Dec 2016)Much of this question and most answers here are now out-of-date as: 1) GData APIsare the previous generation of Google APIs. While not all GData APIs have been deprecated, all modernGoogle APIsdo notuse the Google Data protocol; and 2) Google released a new Google Sheets API v4(not GData) in 2016. In order to use the new API, you need to get the Google APIs Client Library for Javaand use the latest Sheets API, which is much more powerful and flexible than any previous API.

(2016 年 12 月)此问题的大部分内容和此处的大多数答案现已过时,因为:1) GData API是上一代 Google API。虽然不是所有的GData API与已被否决,所有现代谷歌的API没有使用谷歌数据协议; 和 2) 谷在 2016 年发布了新的 Google Sheets API v4(不是 GData)。为了使用新的 API,你需要获取Google APIs Client Library for Java并使用最新的Sheets API,它更强大和比任何以前的 API 都灵活。

Here's our Java Quickstart code sampleto help you get going on using the API -- there's OAuth2 code in it too. Also, here are the JavaDocs reference for the Sheets APIwhich outlines all the classes at your disposal. If you're not "allergic" to Python, I've also made a video walking through the OAuth authorization code and another pair of videos with more "real-world" examples using the Sheets API:

这是我们的 Java 快速入门代码示例,可帮助您继续使用 API——其中也包含 OAuth2 代码。此外,这里是Sheets API 的 JavaDocs 参考,其中概述了您可以使用的所有类。如果您对 Python 不“过敏”,我还制作了一个介绍 OAuth 授权代码的视频和另一对视频,其中包含使用 Sheets API 的更多“真实世界”示例:

The latest API provides features not available in older releases, namely giving developers programmatic access to a Sheet as if you were using the user interface (create frozen rows, perform cell formatting, resizing rows/columns, adding pivot tables, creating charts, etc.) Also note this API is primarily for programmatic spreadsheet operations & functionality as described above.

最新的 API 提供了旧版本中不可用的功能,即让开发人员以编程方式访问工作表,就像您在使用用户界面一样(创建冻结行、执行单元格格式设置、调整行/列大小、添加数据透视表、创建图表等。 ) 另请注意,此 API 主要用于如上所述的程序化电子表格操作和功能。

To perform file-level access such as uploads & downloads, imports & exports (same as uploads & downloads but conversion to/from various formats), you would use the Google Drive APIinstead, and here are a pair of examples I've created (also Python):

要执行文件级访问,例如上传和下载、导入和导出(与上传和下载相同,但可以转换为各种格式),您可以改用Google Drive API,这里有两个我创建的示例(也是 Python):

  • (simple) Exporting a Google Sheet as CSV (blogpost)
  • (intermediate) "Poor man's plain text to PDF" converter (blogpost) (*)
  • (简单)将 Google 表格导出为 CSV(博客文章
  • (中级)“穷人的纯文本转PDF”转换器(博文)(*)

(*) - TL;DR: upload plain text file to Drive, import/convert to Google Docs format, then export that Doc as PDF. Post above uses Drive API v2; this follow-up postdescribes migrating it to Drive API v3, and here's a developer videocombining both posts.

(*) - TL;DR:将纯文本文件上传到云端硬盘,导入/转换为 Google 文档格式,然后将该文档导出为 PDF。上面的帖子使用 Drive API v2;这篇后续文章描述了将其迁移到 Drive API v3,这里有一个结合了这两篇文章的开发人员视频

To learn more about how to use Google APIs (mostly Python or JavaScript), check out the variety of Google developer videos (series 1and series 2) I'm producing.

要了解有关如何使用 Google API(主要是 Python 或 JavaScript)的更多信息,请查看我正在制作的各种 Google 开发人员视频(系列 1系列 2)。