在YouTube API中获取未经授权的访问权限[Xamarin.Forms(Portable)]

时间:2017-03-07 13:46:16

标签: c# youtube xamarin.forms youtube-data-api unauthorized

我正在尝试将视频从Xamarin.Forms(便携式)上传到YouTube,我尝试使用Google APIs,但Google API与Xamarin.Forms(便携式)不兼容在这个阶段。所以,我必须通过HttpClient上传,但我在Unauthorised

获得了StatusCode
public async Task UploadVideoAsync(Stream stream)
{
    //var token = flow.LoadTokenAsync("", CancellationToken.None).Result;
    string json = @"{
                        ""snippet"": {
                        ""title"": ""using API"",
                        ""description"": ""This is a description of my video"",
                        ""tags"": [""cool"", ""video"", ""more keywords""],
                        ""categoryId"": ""21"",
                        },
                        ""status"": {
                        ""privacyStatus"": ""public"",
                        ""embeddable"": true,
                        ""license"": ""youtube""
                        }
                    }";

    var JsonReqMsg = new StringContent(json);

    JsonReqMsg.Headers.ContentType = new MediaTypeHeaderValue("application/json")
    {
        CharSet = "UTF-8"
    };

    var request = new HttpRequestMessage
        (HttpMethod.Post, new Uri("https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status"));
    request.Headers.Add("X-Upload-Content-Length", stream.Length.ToString());
    request.Headers.Add("x-upload-content-type", "video/*");
    request.Content = JsonReqMsg;

    var httpClient = new HttpClient();
    httpClient.DefaultRequestHeaders.Add("Authorization", Constants.API.Google.AccessTokenType + " " + Constants.API.Google.AccessToken);

    var UploadReq = await httpClient.SendAsync(request);
    if (UploadReq.IsSuccessStatusCode)
    {
        IEnumerable<string> _VideoUrl = null;
        var res = await UploadReq.Content.ReadAsStringAsync();
        UploadReq.Headers.TryGetValues("Location", out _VideoUrl);

        var binaryContent = new StreamContent(stream);
        var UploadReq_ = await httpClient.PutAsync(new Uri(_VideoUrl.ToString()), binaryContent);
        if (UploadReq_.IsSuccessStatusCode)
        {
            var res_ = await UploadReq_.Content.ReadAsStringAsync();
        }
    }
}

代码中有什么问题吗?

1 个答案:

答案 0 :(得分:-1)

您的授权不正确。您应该使用“bearer”或开发人员密钥。以下是YouTube文档:https://developers.google.com/youtube/2.0/developers_guide_protocol#OAuth2_Calling_a_Google_API