本文介绍了如何刷新我从 iOS 中的 google oauth 2.0 获得的令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making an iOS application that uses the user's google account to get data from his youtube account and show them ....first step is done using the gtm2 to authenticate the user and get an acces-token and a refresh-tokenthe problem is that the access-token expires after 60 minutes and i have to login and allow the application again...i have found that you can use the refresh-token to get a new access-tokenusing this from the documetation :--> my question is how to make a POST request to get the access token in objective-cthis is the data i need to use:

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

这是我正在使用的代码:

this is the code i am using :

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

我得到的错误是:{错误":无效请求"}

the error i get is :{ "error" : "invalid_request"}

推荐答案

您的格式字符串中缺少 =.

You are missing a = in your format string.

改变

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 中的 google oauth 2.0 获得的令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 19:04