OGeek|极客世界-中国程序员成长平台

标题: ios - AFHTTPSessionManager 设置授权头 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 17:31
标题: ios - AFHTTPSessionManager 设置授权头

我已经被这个问题困扰了一段时间,我正在使用 Youtube 的 api,但我一直收到 403 错误。我正在使用负责 OAuth2 的 Google 登录

 NSString *authToken = [[NSString alloc]initWithFormat"Bearer %@",[Lockbox unarchiveObjectForKey"accessToken"]];

 NSDictionary *parameters = @{@"mine""true", @"part": @"contentDetails"};
 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

 manager.requestSerializer = [AFJSONRequestSerializer serializer];
 [manager.requestSerializer setValue:authToken forHTTPHeaderField"Authorization"];
NSLog(@"%@----------", authToken); //Prints correct value

 [manager GET"https://www.googleapis.com/youtube/v3/channels" parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

我知道 GET url 是正确的,因为我已经尝试在 OAuth 2.0 Playground 上使用它并且得到 200 响应。

以下是我返回的 403 错误响应

{ status code: 403, headers {
"Cache-Control" = "private, max-age=0";
"Content-Encoding" = gzip;
"Content-Length" = 356;
"Content-Type" = "application/json; charset=UTF-8";
Date = "Sat, 17 Sep 2016 08:18:16 GMT";
Expires = "Sat, 17 Sep 2016 08:18:16 GMT";
Server = GSE;
Vary = "Origin, X-Origin";
"alt-svc" = "quic=\":443\"; ma=2592000; v=\"36,35,34,33,32\"";
"x-content-type-options" = nosniff;
"x-frame-options" = SAMEORIGIN;
"x-xss-protection" = "1; mode=block";

} }

我没有在标题中看到 Authorization 字段,但我相信我设置正确并以正确的方式查看 SO。是否有任何明显的问题,因为我已经被困了好几个小时了



Best Answer-推荐答案


NSString *string = [NSString stringWithFormat"https://www.google.com/m8/feeds/contacts/default/full/%@?alt=json",contactID];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod"DELETE" URLString:string parameters:nil error:nil];
NSString *token = [NSString stringWithFormat"Bearer %@",[[GoogleContactManager sharedManager] token]]; //bearer is my personal requirement your's can differ

[req setValue:token forHTTPHeaderField"Authorization"];
[req setValue"3.0" forHTTPHeaderField:@"GData-Version"];
[req setValue:@"*" forHTTPHeaderField:@"if-match"];

关于ios - AFHTTPSessionManager 设置授权头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39544645/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://ogeek.cn/) Powered by Discuz! X3.4