我已经按照 Google Drive SDK 站点上给出的示例进行了通过服务帐户进行授权(https://developers.google.com/drive/service-accounts)并插入文件(https://developers.google.com/驱动器/v2/参考/文件/插入)。我已经设法使用带有 oauth2 的客户端 ID/客户端密码使其工作,但需要自动化,所以想使用私钥。
我的问题是我得到一个文件 ID、标题、描述和 MIME 类型作为回报,例如文件 ID:%s0B6ysbMIcH3AGWHJPRmZUTVZZZMnM,标题:我的文档,描述:测试文档,MIME 类型:文本/纯文本,但文档不存在在驱动器中,没有返回错误。
我已经为此工作了 2 天,但没有成功,非常感谢任何帮助。我在网上查了一下,发现的例子和下面类似。我尝试了多个 Google 帐户(一个是公司 Google Apps,另一个是具有相同结果的普通 gmail 帐户)。
代码(更改了帐户信息):
public class AutoGoogleDrive {
private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "/home/jsmith/Java/11111111111111111111111111-privatekey.p12";
private static final String SERVICE_ACCOUNT_EMAIL = "1111111111111@developer.gserviceaccount.com";
public static Drive getDriveService() throws GeneralSecurityException,
IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(DriveScopes.DRIVE_FILE)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
.build();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).build();
return service;
}
public static void main(String[] args) throws IOException {
Drive service = null;
try {
service = getDriveService();
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Insert a text file
File body = new File();
body.setTitle("My document");
body.setDescription("A test document");
body.setMimeType("text/plain");
// File's content.
java.io.File fileContent = new java.io.File("/home/jsmith/document.txt");
FileContent mediaContent = new FileContent("text/plain", fileContent);
try {
File file = service.files().insert(body, mediaContent).execute();
// Uncomment the following line to print the File ID.
System.out.println("File ID: %s" + file.getId());
System.out.println("Title: " + file.getTitle());
System.out.println("Description: " + file.getDescription());
System.out.println("MIME type: " + file.getMimeType());
} catch (IOException e) {
System.out.println("An error occured: " + e);
}
}
}
谢谢,
乔·史密斯