You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用GoogleCredentials替代废弃的GoogleCredential初始化Google Drive服务

解决方案

你需要使用HttpCredentialsAdapter将新的GoogleCredentials对象包装为Drive构造参数兼容的HttpRequestInitializer实例即可,完整适配代码如下:

import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.services.drive.Drive;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.api.services.drive.DriveScopes;
import java.io.FileInputStream;
import java.util.List;

// 初始化逻辑
JsonFactory JSON_FACTORY = new GsonFactory();

GoogleCredentials credential = GoogleCredentials.fromStream(new FileInputStream("sa.json"))
                .createScoped(List.of(DriveScopes.DRIVE))
                .createDelegated("foo@bar.com");

// 核心适配步骤:将新Credentials转为旧API可识别的初始化器
HttpCredentialsAdapter credentialsAdapter = new HttpCredentialsAdapter(credential);

return new Drive.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, credentialsAdapter)
                .setApplicationName("my-drive-app")
                .build();

说明

  • 你当前使用的依赖版本已经内置HttpCredentialsAdapter,无需新增或修改依赖
  • 该适配器会自动处理令牌刷新、权限校验等逻辑,和原有废弃GoogleCredential的行为完全一致
  • 注意导入包路径为com.google.auth.http.HttpCredentialsAdapter,不要误导入其他同名类

内容的提问来源于stack exchange,提问作者Constantijn Visinescu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 05:18:02