2012-08-01 64 views
0

我正在嘗試實施Google OAuth 2以訪問Google API。 當我嘗試通過訪問令牌交換代碼時,它不起作用。實施Google OAuth 2

我使用這種方法來做到這一點。

(void)getAccessTokenwWithCode:(NSString*)code 
{ 
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[@"https://accounts.google.com/o/oauth2/token" ]]; 
     [request setHTTPMethod:@"POST"]; 
     NSDictionary *postBodyDic = [NSDictionary dictionaryWithObjectsAndKeys: 
          code, @"code", 
          @"my_client_id", @"client_id", 
          @"my_client_secret", @"client_secret", 
          @"http://localhost", @"redirect_uri", 
          @"authorization_code", @"grant_type", 
          nil]; 

    NSString *postBody = [postBodyDic JSONString]; 
    NSData *data = [postBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; 
    [request setHTTPBody:data]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request        
    success:^(NSURLRequest *request, NSURLResponse *response, id JSON) 
    { 
     NSLog(@"%@", JSON); 
    } 
    failure:^(NSURLRequest *request, NSURLResponse *response, NSError *error, id JSON) 
    { 
     NSLog(@"ERROR \n%@", error); 
    } 
    ]; 

    [queue addOperation:operation]; 
} 

我得到一個400錯誤

任何人都可以幫我定位的問題?

在此先感謝。

+0

你能發佈完整的錯誤信息嗎? – 2012-08-01 16:16:36

+0

您將使用哪個Google API(郵件,日曆,分析等) – 2012-08-01 22:19:42

+0

@Claudio Cherubino這是完整的eroor消息Error Domain = com.alamofire.networking.error Code = -1011「Expected status code [索引數量:100(在1範圍內),索引:(200-299)],得到400「UserInfo = 0x1109f850 {NSErrorFailingURLKey = https://accounts.google.com/o/oauth2/token,NSLocalizedDescription =預期狀態代碼 [索引數量:100(在1個範圍內),索引:(200-299)],得到400} – iArezki 2012-08-02 07:51:03

回答