Java Google drive API没有列出我的所有文件
我正在使用一个非常简单的示例在google drive上检索我的文件。有两件奇怪的事Java Google drive API没有列出我的所有文件,java,google-drive-api,Java,Google Drive Api,我正在使用一个非常简单的示例在google drive上检索我的文件。有两件奇怪的事 我第一次运行示例时,google说“应用程序希望访问您的文件”。嗯,我确认了。但是,第二次,它说“应用程序想要离线访问”。。。啊。。。为什么? 可能吧(但我不确定),在我第二次确认之后,我只得到我通过这个应用程序上传的文件 代码是 package com.google.api.services.samples.drive.cmdline; import com.google.api.client.auth.o
package com.google.api.services.samples.drive.cmdline;
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.GoogleUtils;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.media.MediaHttpDownloader;
import com.google.api.client.googleapis.media.MediaHttpUploader;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpTransport;
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.Preconditions;
import com.google.api.client.util.store.DataStoreFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Collections;
import java.util.List;
/**
* A sample application that runs multiple requests against the Drive API. The requests this sample
* makes are:
* <ul>
* <li>Does a resumable media upload</li>
* <li>Updates the uploaded file by renaming it</li>
* <li>Does a resumable media download</li>
* <li>Does a direct media upload</li>
* <li>Does a direct media download</li>
* </ul>
*
* @author rmistry@google.com (Ravi Mistry)
*/
public class DriveSample {
/**
* Be sure to specify the name of your application. If the application name is {@code null} or
* blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
*/
private static final String APPLICATION_NAME = "testing";
private static final String UPLOAD_FILE_PATH = "c:\\Users\\bnie\\workspace\\Servers\\.project";
private static final String DIR_FOR_DOWNLOADS = "c:\\temp";
private static final java.io.File UPLOAD_FILE = new java.io.File(UPLOAD_FILE_PATH);
/** Directory to store user credentials. */
private static final java.io.File DATA_STORE_DIR =
new java.io.File(System.getProperty("user.home"), ".store/drive_sample");
/**
* Global instance of the {@link DataStoreFactory}. The best practice is to make it a single
* globally shared instance across your application.
*/
private static FileDataStoreFactory dataStoreFactory;
/** Global instance of the HTTP transport. */
private static HttpTransport httpTransport;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/** Global Drive API client. */
private static Drive drive;
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
// load client secrets
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(DriveSample.class.getResourceAsStream("/client_secrets.json")));
if (clientSecrets.getDetails().getClientId().startsWith("Enter")
|| clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
System.out.println(
"Enter Client ID and Secret from https://code.google.com/apis/console/?api=drive "
+ "into drive-cmdline-sample/src/main/resources/client_secrets.json");
System.exit(1);
}
// set up authorization code flow
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
JSON_FACTORY, clientSecrets, Collections.singleton(DriveScopes.DRIVE_FILE))
.setDataStoreFactory(dataStoreFactory).build();
// authorize
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
public static void main(String[] args) {
Preconditions.checkArgument(
!UPLOAD_FILE_PATH.startsWith("Enter ") && !DIR_FOR_DOWNLOADS.startsWith("Enter "),
"Please enter the upload file path and download directory in %s", DriveSample.class);
try {
// httpTransport = GoogleNetHttpTransport.newTrustedTransport();
NetHttpTransport.Builder builder = new NetHttpTransport.Builder();
builder.trustCertificates(GoogleUtils.getCertificateTrustStore());
httpTransport = builder.build();
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
// authorization
Credential credential = authorize();
// set up the global Drive instance
drive = new Drive.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
FileList l = drive.files().list().setMaxResults(10).execute();
List<File> files = l.getItems();
if (files == null || files.size() == 0) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getTitle(), file.getId());
}
}
// run commands
// View.header1("Starting Resumable Media Upload");
// File uploadedFile = uploadFile(false);
//
// View.header1("Updating Uploaded File Name");
// File updatedFile = updateFileWithTestSuffix(uploadedFile.getId());
//
// View.header1("Starting Resumable Media Download");
// downloadFile(false, updatedFile);
//
// View.header1("Starting Simple Media Upload");
// uploadedFile = uploadFile(true);
//
// View.header1("Starting Simple Media Download");
// downloadFile(true, uploadedFile);
//
// View.header1("Success!");
return;
} catch (IOException e) {
System.err.println(e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(1);
}
/** Uploads a file using either resumable or direct media upload. */
private static File uploadFile(boolean useDirectUpload) throws IOException {
File fileMetadata = new File();
fileMetadata.setTitle(UPLOAD_FILE.getName());
FileContent mediaContent = new FileContent("image/jpeg", UPLOAD_FILE);
Drive.Files.Insert insert = drive.files().insert(fileMetadata, mediaContent);
MediaHttpUploader uploader = insert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(useDirectUpload);
uploader.setProgressListener(new FileUploadProgressListener());
return insert.execute();
}
/** Updates the name of the uploaded file to have a "drivetest-" prefix. */
private static File updateFileWithTestSuffix(String id) throws IOException {
File fileMetadata = new File();
fileMetadata.setTitle("drivetest-" + UPLOAD_FILE.getName());
Drive.Files.Update update = drive.files().update(id, fileMetadata);
return update.execute();
}
/** Downloads a file using either resumable or direct media download. */
private static void downloadFile(boolean useDirectDownload, File uploadedFile)
throws IOException {
// create parent directory (if necessary)
java.io.File parentDir = new java.io.File(DIR_FOR_DOWNLOADS);
if (!parentDir.exists() && !parentDir.mkdirs()) {
throw new IOException("Unable to create parent directory");
}
OutputStream out = new FileOutputStream(new java.io.File(parentDir, uploadedFile.getTitle()));
MediaHttpDownloader downloader =
new MediaHttpDownloader(httpTransport, drive.getRequestFactory().getInitializer());
downloader.setDirectDownloadEnabled(useDirectDownload);
downloader.setProgressListener(new FileDownloadProgressListener());
downloader.download(new GenericUrl(uploadedFile.getDownloadUrl()), out);
}
}
package com.google.api.services.samples.drive.cmdline;
导入com.google.api.client.auth.oauth2.Credential;
导入com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
导入com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
导入com.google.api.client.googleapis.googlelutils;
导入com.google.api.client.googleapis.auth.oauth2.googleaauthorizationcodeflow;
导入com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
导入com.google.api.client.googleapis.media.mediahtttpdownloader;
导入com.google.api.client.googleapis.media.MediaHttpUploader;
导入com.google.api.client.http.FileContent;
导入com.google.api.client.http.GenericUrl;
导入com.google.api.client.http.HttpTransport;
导入com.google.api.client.http.javanet.NetHttpTransport;
导入com.google.api.client.json.JsonFactory;
导入com.google.api.client.json.jackson2.JacksonFactory;
导入com.google.api.client.util.premissions;
导入com.google.api.client.util.store.DataStoreFactory;
导入com.google.api.client.util.store.FileDataStoreFactory;
导入com.google.api.services.drive.drive;
导入com.google.api.services.drive.DriveScopes;
导入com.google.api.services.drive.model.File;
导入com.google.api.services.drive.model.FileList;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.io.OutputStream;
导入java.net.InetSocketAddress;
导入java.net.Proxy;
导入java.util.Collections;
导入java.util.List;
/**
*针对驱动器API运行多个请求的示例应用程序。客户要求提供此样本
*制造商包括:
*
*- 是否进行可恢复的媒体上载
*- 通过重命名上载的文件来更新该文件
*- 是否进行可恢复的媒体下载
*- 是否直接上传媒体
*- 是否直接下载媒体
*
*
*@作者rmistry@google.com(拉维·米斯特里)
*/
公共类驱动程序示例{
/**
*请确保指定应用程序的名称。如果应用程序名称为{@code null}或
*空白,应用程序将记录警告。建议的格式为“MyCompany ProductName/1.0”。
*/
私有静态最终字符串应用程序\u NAME=“测试”;
私有静态最终字符串上载\u文件\u PATH=“c:\\Users\\bnie\\workspace\\Servers\\.project”;
用于下载的私有静态最终字符串DIR_=“c:\\temp”;
私有静态最终java.io.File UPLOAD\u File=新java.io.File(UPLOAD\u File\u路径);
/**用于存储用户凭据的目录*/
私有静态最终java.io.File数据\u存储\u目录=
新的java.io.File(System.getProperty(“user.home”),“.store/drive_sample”);
/**
*{@link DataStoreFactory}的全局实例。最佳做法是将其设置为单个
*应用程序中的全局共享实例。
*/
私有静态文件数据存储工厂数据存储工厂;
/**HTTP传输的全局实例*/
专用静态HttpTransport-HttpTransport;
/**JSON工厂的全局实例*/
私有静态最终JsonFactory JSON_FACTORY=JacksonFactory.getDefaultInstance();
/**全局驱动器API客户端*/
专用静态驱动器;
/**授权已安装的应用程序访问用户受保护的数据*/
私有静态凭据授权()引发异常{
//加载客户端机密
GoogleClientSecrets clientSecrets=GoogleClientSecrets.load(JSON_工厂,
新的InputStreamReader(DriveSample.class.getResourceAsStream(“/client\u secrets.json”);
if(clientSecrets.getDetails().getClientId().startsWith(“输入”)
||clientSecrets.getDetails().getClientSecret().startsWith(“输入”)){
System.out.println(
“从中输入客户端ID和密码https://code.google.com/apis/console/?api=drive "
+“进入驱动器cmdline sample/src/main/resources/client_secrets.json”);
系统出口(1);
}
//设置授权代码流
GoogleAuthorizationCodeFlow=新的GoogleAuthorizationCodeFlow.Builder(httpTransport,
JSON_工厂、clientSecrets、Collections.singleton(DriveScopes.DRIVE_文件))
.setDataStoreFactory(dataStoreFactory).build();
//授权
返回新的AuthorizationCodeInstalledApp(流,新的LocalServerReceiver())。授权(“用户”);
}
公共静态void main(字符串[]args){
先决条件(
!UPLOAD_FILE_PATH.startsWith(“回车”)和&!DIR_FOR_DOWNLOADS.startsWith(“回车”),
“请输入%s中的上载文件路径和下载目录”,DriveSample.class);
试一试{
//httpTransport=GoogleNetHttpTransport.newTrustedTransport();
NetHttpTransport.Builder=新的NetHttpTransport.Builder();
builder.trustCertificates(GoogleUtils.getCertificateTrustStore());
httpTransport=builder.build();
dataStoreFactory=新文件dataStoreFactory(DATA\u STORE\u DIR);
//授权书
凭证=授权();
//设置全局驱动器实例
drive=new drive.Builder(httpTransport、JSON_工厂、凭证)
.setApplicationName(应用程序名称).build();
FileList l=drive.files().list().setMaxResults(10.execute();
List files=l.getItems();
如果(files==null | | files.size()==0){
System.out.println(“未找到文件”);
}否则{
System.out.println(“文件:”);
用于(文件:文件){
System.out.printf(“%s(%s)\n”),file.getTitle(),fi