如何通过新版Google Photos API获取用户相册列表?
解决Google Photos API获取相册列表返回空JSON的问题
看起来你遇到的问题是用服务账号调用Google Photos API时,虽然返回200状态码,但得到的是空JSON对象{}。我来帮你分析原因并给出解决方案:
核心原因:服务账号无法直接访问普通个人Google Photos相册
Google Photos Library API的服务账号认证机制不支持访问普通Gmail用户的个人相册。服务账号是属于Google Cloud项目的独立实体,它没有自己的Google Photos存储空间,也不能直接模拟普通个人用户(只有G Suite/Workspace域用户支持服务账号模拟)。你代码里的setServiceAccountUser(emailAccount)参数对普通Gmail账号是无效的,所以API返回的是服务账号自己的空相册列表。
解决方案
根据你的使用场景,有两种可行的解决方式:
方案1:改用OAuth 2.0授权码流程(推荐给普通个人用户)
这种方式是让用户主动授权你的应用访问他们的Google Photos库,是Google Photos API推荐的个人用户认证方式。
修改你的认证代码,替换原来的createCredential方法为以下授权码流程实现:
private static Credential getOAuthCredential() throws IOException { // 加载从Google Cloud控制台下载的客户端秘密文件(client_secret.json) InputStream in = YourMainClass.class.getResourceAsStream("/client_secret.json"); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); // 构建授权流程,设置离线访问以便刷新token GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, Collections.singleton(SCOPE)) .setDataStoreFactory(new FileDataStoreFactory(new File("tokens"))) .setAccessType("offline") .build(); // 启动本地服务器接收授权回调 LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build(); String authorizationUrl = flow.newAuthorizationUrl() .setRedirectUri(receiver.getRedirectUri()) .build(); // 引导用户授权 System.out.println("请在浏览器中打开以下链接完成授权:"); System.out.println(authorizationUrl); AuthorizationCodeResponseUrl responseUrl = receiver.waitForCode(); String code = responseUrl.getCode(); // 用授权码交换获取访问token TokenResponse tokenResponse = flow.newTokenRequest(code) .setRedirectUri(receiver.getRedirectUri()) .execute(); // 返回已授权的Credential return flow.createAndStoreCredential(tokenResponse, "user"); }
然后修改main方法,调用这个新的认证方法:
public static void main(String[] args) throws IOException, GeneralSecurityException { Credential credential = getOAuthCredential(); System.out.println(credential.getAccessToken()); doGetRequest(credential.getAccessToken(), "https://photoslibrary.googleapis.com/v1/albums"); }
方案2:针对G Suite/Workspace域用户的服务账号配置
如果你的emailAccount是G Suite/Workspace的域内用户,可以通过以下步骤让服务账号模拟该用户访问相册:
- 登录Google Admin控制台,找到你的服务账号,启用域范围委派
- 给服务账号授予
https://www.googleapis.com/auth/photoslibrary.readonly或对应的权限 - 确保
setServiceAccountUser(emailAccount)设置的是域内的有效用户邮箱
额外检查项
- 确认你的目标账号(不管是个人用户还是域用户)确实存在相册,否则API返回空
{}是正常行为 - 检查请求的Scope是否正确,确保是
https://www.googleapis.com/auth/photoslibrary.readonly(只读)或https://www.googleapis.com/auth/photoslibrary(读写)
内容的提问来源于stack exchange,提问作者ngranin




