2016-11-29 458 views
5

我想使用Java谷歌雲端硬盤API。 我試過這段代碼:com.google.api.client.auth.oauth2.TokenResponseException:401未經授權

public Drive getDriveService() throws GeneralSecurityException, IOException, URISyntaxException 
    { 
     HttpTransport httpTransport = new NetHttpTransport(); 
     JacksonFactory JSON_FACTORY = new JacksonFactory(); 

     GoogleCredential credential = new GoogleCredential.Builder() 
      .setTransport(httpTransport) 
      .setJsonFactory(JSON_FACTORY) 
      .setServiceAccountId("[email protected]") 
      .setServiceAccountPrivateKeyFromP12File(new java.io.File("C:\\buffer\\sonora project-3256770463ed.p12")) 
      .setServiceAccountScopes(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN)) 
      .setServiceAccountUser("[email protected]") 
      .build(); 

     Drive service = new Drive.Builder(httpTransport, JSON_FACTORY, null) 
      .setApplicationName("FileListAccessProject") 
      .setHttpRequestInitializer(credential).build(); 

     return service; 
    } 

但我得到這個錯誤:

An error occurred: com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized 

我使用這種配置:

enter image description here

您能否給一些想法,我怎麼能解決這個問題?

+0

我不另做題沒想到你能請使用setServiceAccountUser,除非它的域管理員帳戶已將服務帳戶添加到管理員帳戶,並且相關用戶也是管理員帳戶上的用戶。 – DaImTo

+0

你可以給它總拋出的錯誤和異常嗎? – Coder

回答

0

在此基礎上SO question,其中一個原因是你的錯誤401,你正在使用的服務帳戶不具有使用與您的Gmail地址相關聯的驅動帳戶。所以,如果你想能夠訪問它上傳的文件,你必須通過服務帳戶授予他們對它們的訪問權限。

這裏是我認爲可以幫助你瞭解更多的服務帳戶

+0

感謝您的回覆,但我仍然無法找到解決方案。你能提供更多的細節嗎? –

相關問題