我試圖爲iOS的youtube應用獲取訪問令牌。以下是我已經從我的viewDidLoad方法中使用的相關代碼:爲youtube api提取訪問令牌iOS「錯誤」:「invalid_request」
mAuth = [[GTMOAuth2Authentication alloc]init];
[mAuth setClientID:@"<MY CLIENT ID>"];
[mAuth setClientSecret:@"<MY CLIENT SECRET>"];
[mAuth setRedirectURI:@"urn:ietf:wg:oauth:2.0:oob"];
[mAuth setScope:@"https://gdata.youtube.com"];
[self.web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://accounts.google.com/o/oauth2/auth?client_id=%@&redirect_uri=%@&scope=%@&response_type=code&access_type=offline", mAuth.clientID, mAuth.redirectURI, mAuth.scope]]]];
在此之後被調用時,用戶必須授予其帳戶的訪問,然後我檢索結果頁面下面的代碼的授權碼:
NSString *string = [self.web stringByEvaluatingJavaScriptFromString:@"document.title"];
if([string rangeOfString:@"Success"].location != NSNotFound){
NSLog(@"This is the code page");
NSString *importantCode = [[string componentsSeparatedByString:@"="] objectAtIndex:1];
NSLog(@"%@", importantCode);
if([self.defaults objectForKey:@"super important code"] == nil){
[self.defaults setObject:importantCode forKey:@"super important code"];
[self.defaults synchronize];
NSString *post = [NSString stringWithFormat:@"code=%@&client_id=%@&client_secret=%@&redirect_uri=%@&grant_type=code", [self.defaults objectForKey:@"super important code"], mAuth.clientID, mAuth.clientSecret, mAuth.redirectURI];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://accounts.google.com/o/oauth2/token"]]];
[request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
[self.web loadRequest:request];
}
[timer invalidate];
}
在那之後,我應該給訪問令牌響應我的POST請求,而是我得到一個網頁,只是說:
{
"error" : "invalid_request"
}
有誰(SE e我錯了哪裏)/(知道如何檢索訪問令牌)?
嗯,我的URI,客戶端ID,客戶端密碼和授權碼都是直接從谷歌複製/解析的,所以我不認爲它可能是其中一個值的拼寫錯誤。谷歌確實爲我提供了兩個URI,但我幾乎不知道任何關於Web事務的信息,而且我也不知道本地主機是否只是一個佔位符名稱。這無關緊要,因爲當我更改URI的值時,以前的步驟不起作用。但是,是的,invalid_request看起來是400。 – ERIC