Google云端硬盘API上传会返回文件ID /标题,但云端硬盘中不存在文档

时间:2012-11-08 16:50:16

标签: google-drive-api

我已按照Google云端硬盘SDK网站上提供的示例进行服务帐户授权(https://developers.google.com/drive/service-accounts)并插入文件(https://developers.google .COM /驱动器/ V2 /参考/文件/插入)。我已经设法使用oauth2使用客户端ID /客户端密钥,但需要自动化,所以想要使用私钥。

我的问题是我获得了文件ID,标题,描述& MIME类型作为回报,例如文件ID:%s0B6ysbMIcH3AGWHJPRmZUTVZZMnM,题目:我的文档,说明:测试文档,MIME类型:text / plain的,但该文件确实在驱动-not-存在并且不返回任何错误。

我已经在这方面工作了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); 
} 

}
}

谢谢,

乔史密斯

1 个答案:

答案 0 :(得分:4)

使用服务帐户时,插入的文件将添加到应用程序的Drive帐户中,而该帐户没有Drive UI。这些文件只能通过API获得。