NSURLConnection授权头不工作 [英] NSURLConnection Authorization Header not Working
问题描述
我尝试通过NSURLConnection在HTTP标头中发送OAuth访问令牌,但它似乎没有发送标头,因为API会给我一个错误,告知必须提供授权令牌。
I am trying to send an OAuth access token in an HTTP header via NSURLConnection but it doesn't seem to be sending the header because the API keeps giving me an error saying that "must provide authorization 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命令的示例:
And this is an example of the cURL command for the API:
curl 'http://generericfakeapi.com/user/profile' -H 'Authorization: OAuth YourAuthToken'
这不是我基本上通过NSURLConnection做的?
Is this not what I am essentially doing through NSURLConnection?
任何帮助将不胜感激。 / p>
Any help would be appreciated.
推荐答案
更改此行:
NSURL *aUrl = [NSURL URLWithString: @"http://generericfakeapi.com/user/profile"];
To:
NSURL *aUrl = [NSURL URLWithString: @"http://generericfakeapi.com/user/profile/"];
显然,如果URL末尾没有斜杠,iOS会删除Authorization标题。这个问题费了我两天睡眠。
Apparently iOS drops the Authorization header if there isn't a slash at the end of a URL. This problem literally cost me my sleep for two days.
这篇关于NSURLConnection授权头不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!