Java环境下YouTube API的OAuth 2.0认证授权求助
用Java实现YouTube API的OAuth2.0授权流程
第一步:准备OAuth2.0凭据
- 登录Google Cloud控制台,找到你的项目,进入「API和服务」→「凭据」
- 创建「OAuth客户端ID」,应用类型选择「桌面应用」(适配本地Java程序)
- 下载生成的
credentials.json文件,放到Java项目的资源目录下
第二步:引入依赖
如果用Maven,在pom.xml中添加Google API客户端相关依赖:
<dependencies> <dependency> <groupId>com.google.api-client</groupId> <artifactId>google-api-client</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>com.google.oauth-client</groupId> <artifactId>google-oauth-client-jetty</artifactId> <version>1.34.1</version> </dependency> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-youtube</artifactId> <version>v3-rev20240505-2.0.0</version> </dependency> </dependencies>
第三步:核心授权与API调用代码
第一次运行会自动打开浏览器,让你登录Google账号完成授权,授权后凭据会存在本地目录,后续运行无需重复授权:
import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.youtube.YouTube; import com.google.api.services.youtube.YouTubeScopes; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.List; public class YouTubeChannelAccess { private static final String APP_NAME = "My YouTube Tool"; private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); // 存储授权令牌的本地目录,可自行修改 private static final String TOKEN_DIR = "youtube-tokens"; // 按需选择权限范围,不要申请超出需求的权限 private static final List<String> SCOPES = Collections.singletonList(YouTubeScopes.YOUTUBE_READONLY); // credentials.json的路径,确保文件存在 private static final String CRED_PATH = "/credentials.json"; private static Credential getAuthCredential(final NetHttpTransport httpTransport) throws IOException { // 加载客户端密钥文件 FileReader secretReader = new FileReader(new File(YouTubeChannelAccess.class.getResource(CRED_PATH).getPath())); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, secretReader); // 构建授权流程 GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, JSON_FACTORY, clientSecrets, SCOPES) .setDataStoreFactory(new FileDataStoreFactory(new File(TOKEN_DIR))) .setAccessType("offline") // 获取刷新令牌,实现长期授权 .build(); // 启动本地服务器接收授权回调 LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build(); return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); } public static void main(String... args) throws IOException, GeneralSecurityException { // 初始化HTTP传输 final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // 获取授权凭据 Credential credential = getAuthCredential(httpTransport); // 创建YouTube服务实例 YouTube youtubeService = new YouTube.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName(APP_NAME) .build(); // 示例:获取当前授权用户的频道信息 YouTube.Channels.List channelRequest = youtubeService.channels().list(Collections.singletonList("snippet,contentDetails")); channelRequest.setMine(true); // 指定获取当前用户的频道 var response = channelRequest.execute(); response.getItems().forEach(channel -> { System.out.println("频道名称:" + channel.getSnippet().getTitle()); System.out.println("频道ID:" + channel.getId()); System.out.println("频道描述:" + channel.getSnippet().getDescription()); }); } }
关键细节说明
- 权限范围(SCOPES):根据实际需求调整,比如上传视频用
YouTubeScopes.YOUTUBE_UPLOAD,全权限用YouTubeScopes.YOUTUBE,权限越小越容易通过授权。 - 离线访问:设置
accessType="offline"才能获取刷新令牌,当访问令牌过期时,客户端会自动刷新,无需重复手动授权。 - 令牌存储:授权后的令牌会存在指定的本地目录,删除该目录可触发重新授权流程。
常见问题排查
- 找不到
credentials.json:确认文件路径正确,或改用绝对路径指定文件位置。 - 权限不足报错:检查
SCOPES是否包含调用API所需的权限,比如获取订阅列表需要YOUTUBE_READONLY或更高权限。 - 刷新令牌失效:删除令牌存储目录,重新运行程序完成授权即可。
内容的提问来源于stack exchange,提问作者jpeg
相关产品推荐
相关产品推荐

