NSURLConnection 授权标头不起作用

2024-03-13

我试图通过 NSURLConnection 在 HTTP 标头中发送 OAuth 访问令牌,但它似乎没有发送标头,因为 API 不断给我一个错误,指出“必须提供授权令牌”。

这是我正在使用的代码:

NSURL *aUrl = [NSURL URLWithString: @"http://generericfakeapi.com/user/profile"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:30.0];

[request addValue:[NSString stringWithFormat:@"OAuth %@", token] forHTTPHeaderField:@"Authorization"];

[request setHTTPMethod:@"GET"];

NSError *error = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error: &error];

NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
NSLog(@"Response : %@", JSONDictionary);

这是 API 的 cURL 命令的示例:

curl 'http://generericfakeapi.com/user/profile' -H 'Authorization: OAuth YourAuthToken'

这不是我本质上通过 NSURLConnection 做的事情吗?

任何帮助,将不胜感激。


更改这一行:

NSURL *aUrl = [NSURL URLWithString: @"http://generericfakeapi.com/user/profile"];

To:

NSURL *aUrl = [NSURL URLWithString: @"http://generericfakeapi.com/user/profile/"];

显然,如果 URL 末尾没有斜杠,iOS 会删除授权标头。这个问题简直让我失眠了两天。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NSURLConnection 授权标头不起作用 的相关文章

随机推荐