我正在尝试通过 NSURLConnection 在 HTTP header 中发送 OAuth 访问 token ,但它似乎没有发送 header ,因为 API 一直给我一个错误,提示“必须提供授权 token ”。
这是我正在使用的代码:
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"];
收件人:
NSURL *aUrl = [NSURL URLWithString: @"http://generericfakeapi.com/user/profile/"];
显然,如果 URL 末尾没有斜杠,iOS 会删除 Authorization header 。这个问题让我整整睡了两天。
关于ios - NSURLConnection 授权 header 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18885587/