1

如何在 Google Oauth 2.0 中获取新的访问令牌?

我试过这个:

    NSString * urlString1 = [NSString stringWithFormat:@"https://accounts.google.com/o/oauth2/token?client_id=my_client_id&client_secret=my_client_secret&refresh_token=%@&grant_type=refresh_token",auth.refreshToken];
    NSURL * url = [NSURL URLWithString:urlString1];   
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    NSURLConnection * connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    [connection start];

但结果是:不允许的方法(错误 405)

也许还有另一种获取新访问令牌的方法?

请帮忙!谢谢!

4

2 回答 2

0

请使用以下代码在 Google Plus 中获取访问令牌

首先替换你- GTMOAuth2Authentication.h文件中的(NSString *)description方法,你肯定会得到 G+ 访问令牌

 - (NSString *)description 
 {
        NSArray *props = [NSArray arrayWithObjects:@"accessToken",nil];//[NSArray arrayWithObjects:@"accessToken", @"refreshToken",@"code", @"assertion", @"expirationDate", @"errorString",nil];
       NSMutableString *valuesStr = [NSMutableString string];
       NSString *separator = @"";
       for (NSString *prop in props) {
       id result = [self valueForKey:prop];
       if (result)
       {
          [valuesStr appendFormat:@"%@",result];
          separator = @", ";
      }
    }

 return [NSString stringWithFormat:@"%@",valuesStr];
}

在 .h 文件中

@class GPPSignInButton;
@interface GPlusView : UIViewController <GPPSignInDelegate>
{
      IBOutlet GPPSignInButton *signInButton;
}

@property (retain, nonatomic) IBOutlet GPPSignInButton *signInButton;

在 .m 文件中

 signInButton_.shouldFetchGoogleUserEmail = TRUE;
 signInButton_.delegate = self;

 signInButton_.clientID = [SamacharAppDelegate clientID];
 signInButton_.scope = [NSArray arrayWithObjects:
                       @"https://www.googleapis.com/auth/plus.me",
                       nil];


 -(void)finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error
 {
     if (error) {
           NSLog(@"Error = %@",error.localizedDescription);
           return;
     }
     NSLog("Auth Data = %@",auth);

   /* Auth Data =  {accessToken="ya29.AHES6ZQYLmSBc9n4pLj9U8OQrFoTDZnGLH8okPkxbda7B0Q", refreshToken="1/puItTB-sqHupfp9qPCKcb6_gWUjgcxwzc9TKJvUwMEI", expirationDate="2012-11-24 13:30:55 +0000"}  */

}

于 2012-11-24T12:32:04.637 回答
0

HTTP 405 表示您正在尝试使用资源不允许的动词。例如POST,在只读GET资源或PUT仅接受POSTs 的写入资源上使用 a。

请参阅亚伯拉罕的回答Google with oauth 2

于 2012-11-24T12:33:45.407 回答