我正在尝试使用youtube api的v3上传一个文件,而不使用c#库。我真的不能使用这个库,因为我正在制作自己的库,允许我使用一些常见的api(youtube、vimeo、facebook等)
我已经得到了我的访问令牌和刷新令牌,这很好。现在我需要使用这里定义的youtube可恢复上传上传文件:
https://developers.google.com/youtube/v3/guides/using_resumable_upload_protocol
但由于某种原因,我的代码返回时出现了401未经授权的错误,但我不明白为什么。这是我创建请求的代码:
private void CreateUploadRequest(SynchronisedAsset asset)
{
var endPoint = api.ApiUrl + "/videos?uploadType=resumable&part=snippet&key=" + api.Tokens.ConsumerKey; // read for the different ways to interact with videos https://developers.google.com/youtube/v3/docs/#Videos
var maxSize = 68719476736; // 64 gig
try
{
var location = CompanyProvider.GetUploadLocation(this.baseUploadDirectory, companyId, FileType.Asset);
var filePath = System.IO.Path.Combine(location, asset.FileName);
using (var data = new FileStream(filePath, FileMode.Open))
{
if (maxSize > data.Length && (asset.MimeType.ToLower().StartsWith("video/") || asset.MimeType.ToLower().Equals("application/octet-stream")))
{
var json = "{ "snippet": { "title": "" + asset.FileName + "", "description": "This is a description of my video" } }";
var buffer = Encoding.ASCII.GetBytes(json);
var request = WebRequest.Create(endPoint);
request.Headers[HttpRequestHeader.Authorization] = string.Format("Bearer {0}", api.Tokens.AccessToken);
request.Headers["X-Upload-Content-Length"] = data.Length.ToString();
request.Headers["X-Upload-Content-Type"] = asset.MimeType;
request.ContentType = "application/json; charset=UTF-8";
request.ContentLength = buffer.Length;
request.Method = "POST";
using (var stream = request.GetRequestStream())
{
stream.Write(buffer, 0, (int)buffer.Length);
}
var response = request.GetResponse();
}
}
}
catch (Exception ex)
{
eventLog.WriteEntry("Error uploading to youtube.nEndpoint: " + endPoint + "n" + ex.ToString(), EventLogEntryType.Error);
}
}
api.ApiUrl为https://www.googleapis.com/youtube/v3.我不确定是否需要密钥,文档中没有显示,但我添加了它,看看是否可以解决未经授权的问题。此外,我想,如果没有密钥,它怎么知道要上传到哪个帐户?
有人能看到我的代码出了什么问题吗?
如有任何帮助,我们将不胜感激。
更新1
经过一段时间的整理,我现在添加了一些代码,在尝试上传之前检查youtube凭据。这是通过以下代码位完成的:
public string GetAuthorizeApplicationUrl()
{
var sb = new StringBuilder();
var dictionary = new Dictionary<string, string>
{
{"client_id", Tokens.ConsumerKey},
{"redirect_uri", callbackUrl},
{"response_type", "code"},
{"scope", "https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/youtubepartner"},
{"approval_prompt", "force"},
{"access_type", "offline"},
{"state", ""}
};
sb.Append(requestTokenUrl);
foreach (var parameter in dictionary)
{
var query = (sb.ToString().Contains("?")) ? "&" : "?";
sb.Append(query + parameter.Key + "=" + parameter.Value);
}
return sb.ToString();
}
这段代码负责构建允许我们请求用户访问的URL。
对于返回到返回URL的代码,我们称之为
public void RequestAccessToken(string code)
{
var dictionary = new Dictionary<string, string>
{
{"code", code},
{"client_id", Tokens.ConsumerKey},
{"client_secret", Tokens.ConsumerSecret},
{"redirect_uri", callbackUrl},
{"grant_type", "authorization_code"}
};
var parameters = NormalizeParameters(dictionary);
var resultString = "";
using (var wc = new WebClient())
{
//wc.Headers[HttpRequestHeader.Host] = "POST";
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
resultString = wc.UploadString(requestAccessTokenUrl, parameters);
}
var json = JObject.Parse(resultString);
Tokens.AccessToken = json["access_token"].ToString();
Tokens.RefreshToken = (json["refresh_token"] != null) ? json["refresh_token"].ToString() : null;
Tokens.Save(companyId);
}
现在,因为我们已经宣布我们的应用程序为离线,所以当我们进行任何api调用时,我们只能使用以下代码:
public bool CheckAccessToken()
{
try
{
RefreshToken(); // Get and store our new tokens
return true;
}
catch
{
return false;
}
}
private void RefreshToken()
{
var dictionary = new Dictionary<string, string>
{
{"refresh_token", Tokens.RefreshToken},
{"client_id", Tokens.ConsumerKey},
{"client_secret", Tokens.ConsumerSecret},
{"grant_type", "refresh_token"}
};
var parameters = NormalizeParameters(dictionary);
var resultString = "";
using (var wc = new WebClient())
{
//wc.Headers[HttpRequestHeader.Host] = "POST";
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
resultString = wc.UploadString(requestAccessTokenUrl, parameters);
}
var json = JObject.Parse(resultString);
Tokens.AccessToken = json["access_token"].ToString();
Tokens.Save(companyId);
}
在我的windows服务中,我有这样的代码:
public void SynchroniseAssets(IEnumerable<SynchronisedAsset> assets)
{
if (api.CheckAccessToken())
{
foreach (var asset in assets)
{
var uploadAssetThread = new Thread(() => CreateUploadRequest(asset));
uploadAssetThread.Start(); // Upload our assets at the same time
}
}
}
正如您所看到的,它调用上面的原始代码。当我把它解析成json时,我得到的错误是:
{
"error":{
"errors":[
{
"domain":"youtube.header",
"reason":"youtubeSignupRequired",
"message":"Unauthorized",
"locationType":"header",
"location":"Authorization"
}
],
"code":401,
"message":"Unauthorized"
}
}
所以,如果有人能帮我弄清楚这意味着什么,那就太好了。
干杯,
/r3plica
"youtubeSignupRequired"的原因通常意味着YouTube帐户没有正确设置,或者您还没有创建YouTube频道。这是上传视频之前的一项要求。如果谷歌能够改进他们在这种情况下的错误消息,并使其更加详细,那就太好了。
返回401未授权的问题是因为我访问的帐户没有关联的youtube帐户。