首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在OAuth中使用Java2.0和Google Spreadsheet API的示例是什么?

在OAuth中使用Java2.0和Google Spreadsheet API的示例是什么?
EN

Stack Overflow用户
提问于 2014-01-30 02:56:32
回答 3查看 13K关注 0票数 17

展示如何使用Google Data Java Client Library及其对Google Spreadsheet API (现在称为Google Sheets API)的OAuth 2.0支持的示例代码在哪里?

EN

回答 3

Stack Overflow用户

发布于 2014-08-23 08:08:52

答案已从原始问题移至匹配网站的"Q and A“格式。

Google Data Java Client Library支持OAuth 2.0。不幸的是,库中没有完整的示例来说明如何在Google Spreadsheet API中使用它。

这是一个对我很有效的例子。我希望有人发现它是有帮助的。

代码语言:javascript
复制
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.jackson.JacksonFactory;
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();
    JacksonFactory jsonFactory = new JacksonFactory();

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

  // …
}

下面是另一个类:

代码语言:javascript
复制
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");
    }

  }

  // ...
}
票数 7
EN

Stack Overflow用户

发布于 2015-10-07 14:59:52

你可以通过示例here找到逐步的解释。因此,您的代码可能如下所示:

代码语言:javascript
复制
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;
}
票数 1
EN

Stack Overflow用户

发布于 2016-12-02 09:57:04

(2016年12月)这个问题的大部分和这里的大多数答案现在已经过时了,因为: 1) GData APIs是上一代的Google API。虽然并不是所有的谷歌API都被弃用,但all Google APIs do not use the Google Data protocol;以及2) 2016年的谷歌released a new Google Sheets API v4 (不是GData)。要使用新的接口,您需要获取the Google APIs Client Library for Java并使用最新的Sheets API,它比任何以前的接口都更强大、更灵活。

这里是帮助您开始使用our Java Quickstart code sample的API --其中也包含OAuth2代码。此外,下面是the JavaDocs reference for the Sheets API,它概述了您可以使用的所有类。如果你对Python不“过敏”,我还制作了一个OAuth授权码的视频,以及使用Sheets API的另两个视频,其中包含更多的“真实世界”示例:

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

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

PDF格式(简单)将谷歌表格导出为CSV (blogpost)

  • (intermediate)“穷人纯文本到”转换器(blogpost) (*)

(*) - TL;DR:上传纯文本文件到驱动器,导入/转换为Google Docs格式,然后将该文档导出为PDF。上面的帖子使用了Drive API v2;this follow-up post描述了将其迁移到Drive API v3,这里有一个结合了这两篇帖子的developer video

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21440101

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档