NSURLConnection授权标头不工作

我试图通过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"]; 

至:

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

如果在URL末尾没有斜线,iOS显然会丢弃授权标头。 这个问题真的让我睡了两天。

对我来说,看起来不错。 你确定你给了一个有效的令牌吗? 尝试赶上这样的错误

 if (error) { NSLog(@"error : %@", error.description); } 

我的代码运作良好:

 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]; 

希望能帮助到你

Interesting Posts