NSURLRequest setValue: forHTTPHeaderField:@“Authorization” not working

五迷三道 提交于 2019-12-23 00:24:04

问题


I try to make an authenticate call to the twitter API with the Application only Authentication API

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] 
                                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData 
                                                   timeoutInterval:20.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"Some App Name" forHTTPHeaderField:@"User-Agent"];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
[request setHTTPBody:[@"grant_type=client_credentials" dataUsingEncoding:NSUTF8StringEncoding]];

Interestingly the authValue is not getting set for HTTPHeaderField @"Authorization". Therefor my calls fail of course. All other header fields are set correctly.

I check it by

NSLog(@"Authorization, %@, %@", [request valueForHTTPHeaderField:@"Authorization"], authValue);

which returns @"Authorization, (null), theCorrectStuff

Why is this happening? I should be able to set it right away, or am I missing something?

Thanks for your time and consideration, Fabian


回答1:


I had the same issue. Output your authValue, it probably contains new lines. For the application only authentication after you do base64 you need to remove new lines from authValue otherwise the header field won't be set.

Or just use already written Objective-C library for Twitter REST API 1.1 (https://github.com/nst/STTwitter).



来源:https://stackoverflow.com/questions/18548248/nsurlrequest-setvalue-forhttpheaderfieldauthorization-not-working

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