2013-11-14 59 views
0

我試圖爲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我錯了哪裏)/(知道如何檢索訪問令牌)?

回答

0

我很想知道HTTP狀態代碼是什麼......我懷疑「invalid_request」意味着400,這幾乎總是意味着在構成您的認證URI的方式中存在一些惱人的愚蠢的小錯誤。我不知道iOS/ObcJ足以告訴您是否已正確地URLescaped任何參數值中的任何有趣的字符,但值得檢查。或者其中一個值的錯字,或者是一個額外的換行符或其他內容?

+0

嗯,我的URI,客戶端ID,客戶端密碼和授權碼都是直接從谷歌複製/解析的,所以我不認爲它可能是其中一個值的拼寫錯誤。谷歌確實爲我提供了兩個URI,但我幾乎不知道任何關於Web事務的信息,而且我也不知道本地主機是否只是一個佔位符名稱。這無關緊要,因爲當我更改URI的值時,以前的步驟不起作用。但是,是的,invalid_request看起來是400。 – ERIC

0

就像這樣簡單,如果你正在閱讀本文並且你使用的是YouTube API,請不要犯同樣的錯誤,我已經將grant_type參數設置爲'code'時它應該是'authorisation_code'。如果您正在閱讀本文,並且您通常發送POST請求,則此錯誤「invalid_request」意味着您要麼跳過了應添加的參數之一,要麼您錯誤地添加了該參數。

相關問題