ios - 如何刷新我在 iOS 中从 google oauth 2.0 获得的 token

标签 ios post youtube-api oauth-2.0

我正在制作一个 iOS 应用程序,它使用用户的 google 帐户从他的 youtube 帐户获取数据并显示它们...... 第一步是使用 gtm2 对用户进行身份验证并获取访问 token 和刷新 token 问题是访问 token 在 60 分钟后过期,我必须再次登录并允许该应用程序... 我发现您可以使用刷新 token 来获取新的访问 token 从文档中使用它: --> 我的问题是如何发出 POST 请求以在 objective-c 中获取访问 token 这是我需要使用的数据:

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);

我得到的错误是: { “错误”:“无效请求”

最佳答案

您的格式字符串中缺少 =

改变

NSString *post =[[NSString alloc] initWithFormat:@"client_secret=%@&grant_type=refresh_token&refresh_token=%@&client_id%@",kGoogleClientSecretKey,kRefreshToken,kGoogleClientIDKey];

NSString *post =[[NSString alloc] initWithFormat:@"client_secret=%@&grant_type=refresh_token&refresh_token=%@&client_id=%@",kGoogleClientSecretKey,kRefreshToken,kGoogleClientIDKey];

关于ios - 如何刷新我在 iOS 中从 google oauth 2.0 获得的 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14014069/

相关文章:

ios - Xcode 5.1 方法搜索只允许一个字符?

php - 在 html 中添加多行时表单的输出给我 Word "ARRAY"

php - 将php代码添加到mysql数据库中的动态主页模板

android - 在 kotlin 的 api 中发送不同类型的 post 参数

java - YouTubePlayerView 只能使用扩展 YouTubeBaseActivity 作为其上下文的 Activity 创建

ios - cocos2d的某些方面不能与spritebuilder一起使用?

ios - 设置包值返回 nil

ios - 如何检测 30 秒持续时间

ios - 某些youtube视频无法在UIWebView中播放吗?

c# - 从 YouTube 下载视频