2013-05-16 105 views
1

我正嘗試使用谷歌服務帳戶將文件上傳到谷歌硬盤。無法將文件從服務帳戶上傳到Google雲端硬盤

司機服務

public static Drive getDriveService(String secretKeyFile) 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) 
     .setServiceAccountPrivateKeyFromP12File(
      new java.io.File(secretKeyFile)) 
     .build(); 
    Drive service = new Drive.Builder(httpTransport, jsonFactory, null) 
     .setHttpRequestInitializer(credential).setApplicationName("appl name").build(); 
    return service; 
} 



插入文件

private static File insertFile(Drive service, String title, String description,String mimeType, String filename) { 
    File body = new File(); 
    body.setTitle(title); 
    body.setDescription(description); 
    body.setMimeType(mimeType); 

    java.io.File fileContent = new java.io.File(filename); 
    FileContent mediaContent = new FileContent(mimeType, fileContent); 
    try { 
     File file = service.files().insert(body, mediaContent).execute(); 
     return file; 
    } catch (IOException e) { 
     System.out.println("An error occured: " + e); 
     return null; 
    } 
    } 



主要方法

 Drive service=null; 
     try { 
      String secretFile= "somedigit-privatekey.p12"; 
      service = getDriveService(secretFile); 
     } catch (URISyntaxException ex) { 
      ex.printStackTrace(); 
     } 
    File insertFile = insertFile(service, "test title", "File description", "text/plain", "c:\\test.txt"); 
List list = service.files().list(); 
System.out.println("Files Id : "+insertFile.getId()); 
System.out.println("Count Files : "+list.size()); 



現在,我的問題是:

  • 如何以及在哪裏可以查看該文件被上傳?
  • 爲什麼它返回文件ID,但list.size()爲零。
  • 它也會返回下載鏈接,但是當我將該鏈接粘貼到 瀏覽器中時,它不會下載任何文件。
+0

最好爲每個問題啓動個別主題。不過,我會在下面提供一個答案。 –

+0

你可以這樣做?我有同樣的問題:( – victorpacheco3107

+0

我的問題:http://stackoverflow.com/questions/26146712/upload-file-to-google-drive-in-java-without-oauth – victorpacheco3107

回答

3

您正在創建列表請求但未執行它。使用execute方法發出請求:

service.files().list().execute(); 

如果粘貼下載鏈接到瀏覽器,它會與401迴應,因爲你的下載請求,還應該包含一個有效的授權頭。使用以下片段以編程方式下載該文件。

HttpResponse resp = service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute(); 
InputStream stream = resp.getContent(); 

stream是文件內容的輸入流。

或將Authorization: Bearer <access token>添加到您在其他地方製作的請求中。

相關問題