如何使用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
相关产品推荐
相关产品推荐

