NSURLConnection授权标头无法正常工作

har*_*aac 18 curl nsurlconnection http-headers ios get-request

我试图通过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);
Run Code Online (Sandbox Code Playgroud)

这是API的cURL命令的示例:

curl 'http://generericfakeapi.com/user/profile' -H 'Authorization: OAuth YourAuthToken'
Run Code Online (Sandbox Code Playgroud)

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

任何帮助,将不胜感激.

isa*_*air 51

改变这一行:

NSURL *aUrl = [NSURL URLWithString: @"http://generericfakeapi.com/user/profile"];
Run Code Online (Sandbox Code Playgroud)

至:

NSURL *aUrl = [NSURL URLWithString: @"http://generericfakeapi.com/user/profile/"];
Run Code Online (Sandbox Code Playgroud)

显然,iOS的下降Authorization头如果没有在网址的结尾斜线.这个问题硬是花了我我睡了两天.


Mar*_*vec 1

对我来说它看起来不错。您确定您提供了有效的令牌吗?尝试捕获这样的错误

if (error) {
    NSLog(@"error : %@", error.description);
}
Run Code Online (Sandbox Code Playgroud)

我的代码运行良好:

NSURL *jsonURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://....ID=%i", cellID]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:jsonURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0];
[request setValue:@"Basic ...." forHTTPHeaderField:@"Authorization"];
NSURLResponse *response;
NSError * error  = nil;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你