我正在尝试获取适用于 iOS 的 youtube 应用程序的访问令牌。这是我在 viewDidLoad 方法中使用的相关代码:
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"
}
有谁(看看我哪里出错了)/(知道如何检索访问令牌)?