【发布时间】:2012-12-10 10:42:40
【问题描述】:
我正在制作一个 iOS 应用程序,它使用用户的 google 帐户从他的 youtube 帐户获取数据并显示给他们...... 第一步是使用 gtm2 对用户进行身份验证并获取访问令牌和刷新令牌 问题是访问令牌在 60 分钟后过期,我必须登录并再次允许应用程序... 我发现您可以使用刷新令牌来获取新的访问令牌 从文档中使用它: --> 我的问题是如何发出 POST 请求以获取 Objective-c 中的访问令牌 这是我需要使用的数据:
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
client_id=21302922996.apps.googleusercontent.com&
client_secret=XTHhXh1SlUNgvyWGwDk1EjXB&
refresh_token=1/6BMfW9j53gdGImsixUH6kU5RsR4zwI9lUVX-tqf8JXQ&
grant_type=refresh_token
这是我正在使用的代码:
NSString *post =[[NSString alloc] initWithFormat:@"client_secret=%@&grant_type=refresh_token&refresh_token=%@&client_id%@",kGoogleClientSecretKey,kRefreshToken,kGoogleClientIDKey];
NSLog(@"%@",post);
NSURL *url=[NSURL URLWithString:@"https://accounts.google.com/o/oauth2/token"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"%@",data);
我得到的错误是: { “错误”:“无效请求” }
【问题讨论】:
-
我不熟悉 Objective-C 客户端库,但大多数其他语言的客户端库都支持在您使用过期访问权限发出请求时为您自动刷新 OAuth 2 令牌令牌。您确定需要手动刷新吗?如果是这样,最好问的地方可能是groups.google.com/forum/?fromgroups#!forum/…
标签: ios post youtube-api oauth-2.0