我想上傳一個使用YouTube的api v3文件,而不使用c#庫。我真的不能使用庫,因爲我正在製作我自己的庫,允許我使用一些常見的apis(youtube,vimeo,facebook等)Youtube v3 api 401未授權
我已經得到了我的訪問令牌和刷新令牌,這很好。現在我需要用這裏定義的YouTube的斷點續傳上傳文件:
https://developers.google.com/youtube/v3/guides/using_resumable_upload_protocol
但由於某種原因我的代碼是回來了一個401 Unauthorized錯誤,但我不明白爲什麼。 這裏是我的代碼,該代碼創建請求:
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
}
}
}
其爲y你可以看到調用上面的原始代碼。 當我解析成JSON,我正的錯誤是這樣的:
{
"error":{
"errors":[
{
"domain":"youtube.header",
"reason":"youtubeSignupRequired",
"message":"Unauthorized",
"locationType":"header",
"location":"Authorization"
}
],
"code":401,
"message":"Unauthorized"
}
}
所以,如果有人可以幫助我找出這意味着什麼,那將是巨大的。
乾杯,
/r3plica
[Youtube v3 API請求實體太大]的可能重複(http://stackoverflow.com/questions/17279055/youtube-v3-api-request-entity-too-large) –
不是重複的伴侶,我開始一個新的,因爲我的代碼現在是不同的。此外,我現在已經更新:) – r3plica