首页 文章

Youtube API v3 .NET集成

提问于
浏览
1

我在你的应用程序中集成了youtube api v2 . 我有API密钥,我想集成Youtube API v3,但是我收到错误401(响应状态代码并不表示成功)

Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务),位于c:\ code \的Google.Apis.Upload.ResumableUpload`1.d__0.MoveNext()中的Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(任务任务) google.com \ google-api-dotnet-client \ default \ Tools \ Google.Apis.Release \ bin \ Debug \ output \ default \ Src \ GoogleApis \ Apis [Media] \ Upload \ ResumableUpload.cs:第377行

这是相关的代码:

var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
    ApiKey = "myapikey",
    ApplicationName = ConfigurationManager.AppSettings["YoutubeApplicationName"].ToString(),
});

var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = "Default Video Title";
video.Snippet.Description = "Default Video Description";
video.Snippet.Tags = new string[] { "tag1", "tag2" };
video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
var filePath = @"REPLACE_ME.mp4"; // Replace with path to actual movie file.

using (streamVideo)
{
    var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", streamVideo, "video/*");
    videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
    videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

    await videosInsertRequest.UploadAsync();
}

2 回答

  • 0

    YouTube API error reference将错误401列为 authorizationRequiredyoutubeSignupRequired (在“请求上下文错误” Headers 下) . 我可以看到异常的实际HTTP响应 .

    将您的代码与sample code进行比较,您似乎没有使用YouTube用户的凭据传递 HttpClientInitializer 值 . YouTube需要此功能来确定要将视频上传到哪个 Channels .

    相关片段:

    UserCredential credential; 
      using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) 
      { 
        credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( 
            GoogleClientSecrets.Load(stream).Secrets, 
            // This OAuth 2.0 access scope allows an application to upload files to the 
            // authenticated user's YouTube channel, but doesn't allow other types of access. 
            new[] { YouTubeService.Scope.YoutubeUpload }, 
            "user", 
            CancellationToken.None 
        ); 
      } 
    
      var youtubeService = new YouTubeService(new BaseClientService.Initializer() 
      { 
        HttpClientInitializer = credential, 
        ApplicationName = Assembly.GetExecutingAssembly().GetName().Name 
      });
    
  • 0

    我找到了解决方案 . 代码无效,因为应用程序托管在IIS上 . IIS访问%appdata%文件夹中的文件夹可能存在问题 . 令牌文件默认保存在%appdata%文件夹中 . 我尝试更改该文件夹的权限 . 我添加了Everyone,DefaultAppPool,I_USER,......但没有成功 . 还有更新版本的Google.Apis(1.8.2)允许完整路径( new FileDataStore(fullPath,true)true 表示完整路径,但即使存在错误 . 使用该构造函数是不可能的,因为我总是会收到错误 . 所以我决定我的应用程序应该使用IIS Express(实际上我创建了带有授权代码的新项目) . 转到解决方案属性并使用IIS Express设置应用程序 .

    • https://console.developers.google.com获取cliendId(json文件)(选择Web应用程序)并为javascript起点设置 http:// localhost:48372 (或任何您的应用程序端口使用),并为重定向URL设置 http:// localhost:48372/authorize.aspx . 您还应该在互联网上找到如何使您的端口静态) . 保存您的clientId文件 . (这个步骤你可能已经做过了)

    • 当您使用IIS express时,AuthorizeAsync方法应该没有问题 . 您将被要求输入您的凭据并选择您的YouTube帐户(或者如果您已经进入帐户,则选择帐户) . 当您授予应用程序权限时,您将被重定向到authorize.aspx . 您的授权aspx页面应该创建新的IAuthorization流对象,并提供Client Secret属性和DataStore proprty . 使用 code= Request.Params["code"] 从URL读取代码并创建 UserCredential 对象 . youtubeService的 HttpClientInitializer 属性的类型为 UserCredential . 您应该使用的方法类似于var usercredential = flow.SomeMethodWhichReceives("user",code,CancelletionToken.None) . 之后,在您指定的 FileDataStore 文件夹中生成包含刷新令牌的文件 .

    • 当你有刷新令牌时,你可以做任何你想做的事情,因为刷新令牌应该永远持续(除非手动撤销) . 有一种方法,允许从refreshtoken获取usercredential,如 flow.getAccessTokenfromRefreshToken("user","your_refresh_token_string")

    因此,当您拥有刷新令牌并使用方法last方法时,您将能够访问google youtube api . 您也可以使用此方法将其他用户上传到您的YouTube帐户 . 如果您认为用户在您的帐户中添加的内容,您可以随时制作他们私下上传的视频,并在验证时将其更改为公开 .

    google youtube api中的一些方法需要OAUTH2身份验证(从客户端秘密获取刷新令牌 - >从刷新令牌获取访问令牌...),例如上传视频,但有些像getvideos不需要 . 您可以为youtubeService结构提供API密钥而不是 UserCredential

    编辑:还有一个我忘了提到的捕获(对于那些认为这就是全部的人) . 当您授予应用访问google api的权限时(在您被重定向到authorize.aspx之前),您将收到错误redirect_url不匹配,因为url parametar redirect_url 中的某个地方与您在ClientId中提供的重定向网址不匹配json,(端口是不同的,至少,由于某种原因) . 更改此参数,以便与您在clientId json中提供的重定向URL匹配 .

相关问题