我想使用Java Google Drive API。 我试过这段代码: pre $ public $ getDriveService()抛出GeneralSecurityException,IOException,URISyntaxException { HttpTransport httpTransport = new NetHttpTransport(); JacksonFactory JSON_FACTORY = new JacksonFactory(); GoogleCredential凭证=新的GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountId(sonoratestw-226 @ sonora-project .iam.gserviceaccount) .setServiceAccountPrivateKeyFromP12File(new java.io.File(C:\\buffer\\sonora project-3256770463ed.p12)) .setServiceAccountScopes( Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN)) .setServiceAccountUser(sonoratestw@gmail) .build(); Drive service = new Drive.Builder(httpTransport,JSON_FACTORY,null) .setApplicationName(FileListAccessProject) .setHttpRequestInitializer(凭证).build(); 退货服务; }
但是我得到这个错误:
发生错误:com.google.api.client.auth.oauth2.TokenResponseException:401未授权我使用此配置:
你可以给我一些想法,我可以解决这个问题吗? 解决方案
一个href =stackoverflow/questions/29277025> SO问题,您得到错误401的原因之一是您正在使用的服务帐户无法访问关联的驱动器帐户与您的Gmail地址。所以,如果你想能够访问它上传的文件,你必须授予自己通过服务帐户访问他们的权限。
以下是我认为可以解决的其他SO问题帮助您更好地了解服务帐户。
-
google oauth2用user@gmail冒充服务帐户
Google驱动api服务帐户视图使用java将上传的文件上传到Google Drive -
I want to use Java Google Drive API. I tried this code:
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("sonoratestw-226@sonora-project.iam.gserviceaccount") .setServiceAccountPrivateKeyFromP12File(new java.io.File("C:\\buffer\\sonora project-3256770463ed.p12")) .setServiceAccountScopes(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN)) .setServiceAccountUser("sonoratestw@gmail") .build(); Drive service = new Drive.Builder(httpTransport, JSON_FACTORY, null) .setApplicationName("FileListAccessProject") .setHttpRequestInitializer(credential).build(); return service; }But I get this error:
An error occurred: com.google.api.client.auth.oauth2.TokenResponseException: 401 UnauthorizedI use this configuration:
Can you give some idea how I can fix this?
解决方案Based on this SO question, one reason that you get the error 401 is that the service account you are using doesn't have access to the drive account associated with your Gmail address. So if you want to be able to access the files it uploads you must grant yourself access to them though the service account.
Here are the other SO questions that I think can help you to understand more the service account
google oauth2 impersonate service account with user@gmail
Google drive api services account view uploaded files to google drive using java
Google Drive changing permissions by service account
更多推荐
com.google.api.client.auth.oauth2.TokenResponseException:401未经授权
发布评论