如何使用GoogleCredentials创建Gmail服务?解决编译错误
基于GoogleCredentials创建Gmail服务的编译错误解决方法
问题背景
使用的Maven依赖:
<dependency> <groupId>com.google.api-client</groupId> <artifactId>google-api-client</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>com.google.auth</groupId> <artifactId>google-auth-library-oauth2-http</artifactId> <version>1.25.0</version> </dependency> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-gmail</artifactId> <version>v1-rev20240520-2.0.0</version> </dependency>
按照官方文档编写Gmail客户端代码时,采用GoogleCredentials替代已弃用的GoogleCredential,但触发编译错误:GoogleCredentials不属于HttpRequestInitializer类型,原代码如下:
GoogleCredentials credentials = GoogleCredentials.newBuilder() .setAccessToken( AccessToken.newBuilder() .setTokenValue(googleTokenResult.getAccessToken()) .setExpirationTime(new Date(googleTokenResult.accessTokenExpirationUnixTime)) .setScopes(SCOPES) .build() ) .build(); Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentials) .setApplicationName(APPLICATION_NAME) .build();
解决方法
GoogleCredentials本身并未实现HttpRequestInitializer接口,需要通过HttpCredentialsAdapter类完成适配——这是Google Auth库提供的专门用于将GoogleCredentials转换为HttpRequestInitializer的工具类。
修改后的代码如下:
import com.google.auth.http.HttpCredentialsAdapter; // 保留原凭证创建逻辑 GoogleCredentials credentials = GoogleCredentials.newBuilder() .setAccessToken( AccessToken.newBuilder() .setTokenValue(googleTokenResult.getAccessToken()) .setExpirationTime(new Date(googleTokenResult.accessTokenExpirationUnixTime)) .setScopes(SCOPES) .build() ) .build(); // 用HttpCredentialsAdapter包装凭证,转换为HttpRequestInitializer类型 HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); // 创建Gmail服务时传入适配后的实例 Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer) .setApplicationName(APPLICATION_NAME) .build();
当前使用的google-auth-library-oauth2-http:1.25.0版本已包含HttpCredentialsAdapter,无需额外添加依赖。
内容的提问来源于stack exchange,提问作者HeronAlgoSearch
相关产品推荐
相关产品推荐

