如何通过Java使用Google Drive API获取Google文档内容?

huangapple go评论88阅读模式
英文:

How to get Gdoc content from Google Drive API in Java?

问题

我正在尝试使用Google Drive API获取Google Docs的内容。我已经成功获取了文件夹并获得了Google Docs文件的ID。

在API文档中,提到可以这样下载文件:

private String getGdoc(String id) throws Exception {
    if (service == null) throw new Exception();
    OutputStream outputStream = new ByteArrayOutputStream();
    service.files().export(id, "text/plain")
        .executeMediaAndDownloadTo(outputStream);
    
    return null;
}

我的问题是,我不想使用OutputStream将其写入文件,而是想将文件内容获取到一个String中。

所以我尝试使用InputStream

private String getGdoc(String id) throws Exception {
    if (service == null) throw new Exception();
    InputStream inputStream = service.files().export(id, "text/plain")
        .executeMediaAsInputStream();
    
    System.out.println(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
    
    return null;
}

使用InputStream,我可以获取文件的内容,但是我的文档中有一些日文字符,它们没有显示出来。对于这些日文字符,控制台中只显示?。我不知道这可能是什么原因,因为我已经指定使用了UTF-8字符集。

当我尝试使用OutputStream将其写入txt文件时,没有出现任何字符无法识别的问题。

我不知道最佳实现方法是什么。你能帮助我吗?

英文:

I'm trying to get the content of a Google Docs with the Google Drive API. I successfully fetched folder and got the Google Docs files id.

On the API documentation, it is said that I can download a file like this :

private String getGdoc(String id) throws Exception {
    	if(service == null) throw new Exception();
    	OutputStream outputStream = new ByteArrayOutputStream();
    	service.files().export(id, "text/plain")
    	    .executeMediaAndDownloadTo(outputStream);
    	
    	return null;
    }

My problem is that I don't want to write it into a file with an OutputStream but I want to get the content of the file into a String.

So I tried to use an InputStream :

private String getGdoc(String id) throws Exception {
    	if(service == null) throw new Exception();
    	InputStream inputStream = service.files().export(id, "text/plain")
    	    .executeMediaAsInputStream();
    	
    	System.out.println(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
    	
    	return null;
    }

With an InputStream I get the content of the file, however I have some Japanese characters in my documents and they are not displayed. I only get ? for these Japanese characters in the console. I don't know where it can come from since I specified to use the UTF-8 charset.

When I try to write with the OutputStream into a txt file, I don't have any problem of characters not recognized.

I don't know what is the best way to achieve that. Can you help me ?

答案1

得分: 1

谷歌云盘 API 是一个文件存储 API。它允许您上传和下载存储在谷歌云盘中的文件。在下载文件时,您应该将其保存到您的计算机上,然后在第三方应用程序中打开它。

如果您想要查看和操作存储在谷歌云盘上的谷歌文档文件的内容,您应该考虑使用 Google 文档 API

Google 文档 Java 快速入门

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.docs.v1.Docs;
import com.google.api.services.docs.v1.DocsScopes;
import com.google.api.services.docs.v1.model.Document;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class DocsQuickstart {
    private static final String APPLICATION_NAME = "Google Docs API Java Quickstart";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String TOKENS_DIRECTORY_PATH = "tokens";
    private static final String DOCUMENT_ID = "195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE";

    /**
     * Global instance of the scopes required by this quickstart.
     * If modifying these scopes, delete your previously saved tokens/ folder.
     */
    private static final List<String> SCOPES = Collections.singletonList(DocsScopes.DOCUMENTS_READONLY);
    private static final String CREDENTIALS_FILE_PATH = "/credentials.json";

    /**
     * Creates an authorized Credential object.
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws IOException If the credentials.json file cannot be found.
     */
    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        // Load client secrets.
        InputStream in = DocsQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (in == null) {
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("offline")
                .build();
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
        return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
    }

    public static void main(String... args) throws IOException, GeneralSecurityException {
        // Build a new authorized API client service.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Docs service = new Docs.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();

        // Prints the title of the requested doc:
        // https://docs.google.com/document/d/195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE/edit
        Document response = service.documents().get(DOCUMENT_ID).execute();
        String title = response.getTitle();

        System.out.printf("The title of the doc is: %s\n", title);
    }
}
英文:

The google Drive api is a file storage api. It will let you upload and download files stored within google drive. When downloading the file it is intended that you would save it to your machine and then open it in a third party application.

If you want to examine and manipulate the contents of a google document file stored on Google drive. You should consider using the Google docs api

Google Docs Java quickstart

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.docs.v1.Docs;
import com.google.api.services.docs.v1.DocsScopes;
import com.google.api.services.docs.v1.model.Document;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
public class DocsQuickstart {
private static final String APPLICATION_NAME = &quot;Google Docs API Java Quickstart&quot;;
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = &quot;tokens&quot;;
private static final String DOCUMENT_ID = &quot;195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE&quot;;
/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
private static final List&lt;String&gt; SCOPES = Collections.singletonList(DocsScopes.DOCUMENTS_READONLY);
private static final String CREDENTIALS_FILE_PATH = &quot;/credentials.json&quot;;
/**
* Creates an authorized Credential object.
* @param HTTP_TRANSPORT The network HTTP Transport.
* @return An authorized Credential object.
* @throws IOException If the credentials.json file cannot be found.
*/
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = DocsQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException(&quot;Resource not found: &quot; + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType(&quot;offline&quot;)
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize(&quot;user&quot;);
}
public static void main(String... args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Docs service = new Docs.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
// Prints the title of the requested doc:
// https://docs.google.com/document/d/195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE/edit
Document response = service.documents().get(DOCUMENT_ID).execute();
String title = response.getTitle();
System.out.printf(&quot;The title of the doc is: %s\n&quot;, title);
}
}

huangapple
  • 本文由 发表于 2020年8月17日 07:26:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63442842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定