NSURLConnection Authorization Header not Working

拈花ヽ惹草 提交于 2019-12-03 05:02:49

问题


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".

This is the code that I am using:

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

And this is an example of the cURL command for the API:

curl 'http://generericfakeapi.com/user/profile' -H 'Authorization: OAuth YourAuthToken'

Is this not what I am essentially doing through NSURLConnection?

Any help would be appreciated.


回答1:


Change this line:

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

To:

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

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.




回答2:


For me it look fine. Are you sure you gave a valid token? Try catch the error like this

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

My code work well :

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

hope it helps




回答3:


I had same problem. In my case I changed "http" to "https" and everything works fine



来源:https://stackoverflow.com/questions/18885587/nsurlconnection-authorization-header-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!