ios - NSURLConnection 授权 header 不起作用

标签 ios curl http-headers nsurlconnection get-request

我正在尝试通过 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/

相关文章:

ios - Xcode 开发团队未显示(无法找到您所属的给定团队 ID 'xxxxxx' 的团队。)

linux - shell bash 代码未运行且没有错误警告

php - Nominatim 应用程序错误 PHP

c++ - C++ curl如何使用?

header - .NET HttpWebResponse 不提供位置 header

ios - 如何将 activityindicator 放在 tableview 的中间

ios - SKProductsRequest - 如何处理超时/连接错误?

iOS - 是否有其他像 KeyChain 这样安全但在删除应用程序时被删除的东西?

http - 如何在 Mule cxf 中禁用分块编码 :proxy-client

javascript - 在 javascript 中使用 fetch 时访问 header