2016-11-29 278 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

感谢您的回复,但我仍然无法找到解决方案。你能提供更多的细节吗? –