15

Wo ist ein Beispielcode, der zeigt, wie man die Google Data Java Client Library und ihre Unterstützung für OAuth 2.0 mit der Google Spreadsheet API (jetzt Google Sheets API genannt) verwendet?Was ist ein Beispiel für die Verwendung von OAuth 2.0 und Google Spreadsheet API mit Java?

+0

Sieht gut aus. Fügen Sie möglicherweise Code hinzu, um das Zugriffstoken vom Aktualisierungstoken abzurufen. ... wäre auch passend, dies in Frage- und Antwortformat umzuwandeln. – eddyparkinson

+1

Hmm, das ist eine Antwort, die sich als Frage tarnt ?! ... Ich denke, ich werde das als Q und A restrukturieren. – ErstwhileIII

Antwort

6

Die Antwort wurde von der ursprünglichen Frage an die Site "Q and A" angepasst.

Die Google Data Java Client Library unterstützt OAuth 2.0. Leider gibt es keine vollständigen Beispiele in der Bibliothek, die zeigen, wie man es mit der Google Spreadsheet API verwendet.

Hier ist ein Beispiel, das für mich gearbeitet hat. Ich hoffe, jemand findet es hilfreich.

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

    // … 
} 

Hier ist die andere Klasse:

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

    } 

    // ... 
} 
+0

das hat mir sehr geholfen, danke. Es sollte beachtet werden, dass Sie in den meisten Fällen tatsächlich auf die Tabelle mit Refresh-Token Zugriff Token zugreifen möchten –

+0

@MoscheShaham Ich denke, du meinst: Das Access-Token läuft nach etwa 1 Stunde ab und Sie müssen ein neues Access-Token mit der Aktualisierung erhalten Zeichen. – eddyparkinson

+3

in Android-Anwendung (installierte Anwendung) Google bietet nur Client-ID (nicht Client-Geheimnis). Ich möchte eine Google-Tabelle von meiner Android-App aus bearbeiten, wie soll ich dieses Beispiel ohne Client-Secret verwenden? –

1

Sie einen Schritt here Schritt Erklärung mit Beispielen finden. Als Ergebnis könnte Ihr Code wie folgt aussehen:

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; 
} 
0

(Dezember 2016) Ein großer Teil dieser Frage und die meisten hier Antworten sind jetzt out-of-date wie: 1) GData APIs die vorherige Generation von Google sind APIs. Während nicht alle GData-APIs veraltet sind, verwenden Sie all modern Google APIs do nicht verwenden Sie the Google Data protocol; und 2) Google released a new Google Sheets API v4 (nicht GData) im Jahr 2016. Um die neue API zu verwenden, müssen Sie the Google APIs Client Library for Java und verwenden Sie die neuesten Sheets API, die viel leistungsfähiger und flexibler als jede vorherige API ist.

Hier ist our Java Quickstart code sample, damit Sie mit der API weitermachen können - es gibt auch OAuth2-Code. Auch hier sind the JavaDocs reference for the Sheets API, die alle Klassen zu Ihrer Verfügung umreißt. Wenn Sie nicht „allergisch“ auf Python sind, habe ich gemacht auch ein Video über den OAuth Autorisierungscode zu Fuß und ein anderes Paar von Videos mit mehr „real-world“ Beispielen, die die Blätter API:

Die neueste API bietet Funktionen, die nicht in ol Die Releases geben Entwicklern programmatischen Zugriff auf ein Sheet, als ob Sie die Benutzeroberfläche verwenden würden (fixierte Zeilen erstellen, Zellen formatieren, Zeilen/Spalten skalieren, Pivot-Tabellen hinzufügen, Diagramme erstellen usw.). Beachten Sie auch, dass diese API hauptsächlich für programmatische Tabellenkalkulationsoperationen & Funktionalität wie oben beschrieben.

Um Zugriff auf Dateiebene wie Uploads & Downloads, Importe & Exporte (wie bei Uploads & Downloads aber Umwandlung in/aus verschiedenen Formaten) ausführen, können Sie die Google Drive API stattdessen verwenden würde, und hier sind ein paar Beispiele, die ich‘ ve erstellt (auch Python):

  • (einfach) Exportieren eine Google-Tabelle als CSV (blogpost)
  • (Zwischen-) "Klartext PDF des armen Mannes" Wandler (blogpost) (*)

(*) - TL; DR: Hochladen der Textdatei in Google Drive, Importieren/Konvertieren in das Google Docs-Format, Exportieren des Dokuments als PDF. Der obige Beitrag verwendet Drive API v2; this follow-up post beschreibt die Migration zu Drive API v3, und hier ist eine developer video kombiniert beide Beiträge.

Um mehr über die Verwendung von Google-APIs (hauptsächlich Python oder JavaScript) zu erfahren, werfen Sie einen Blick auf die Vielzahl von Google-Entwicklervideos (series 1 und series 2), die ich produziere.

Verwandte Themen