How to pass authorization token header objective c?

≯℡__Kan透↙ 提交于 2019-12-13 08:46:58

问题


I'm passing username,password for an API call it returns right value. But after authentication API returns an security token I need to capture the token and pass along with username and password.I'm doing the same but it returns forbidden error which denotes invalid token error.I also tried base64 to pass token as suggested at some answer in stackoverflow.The code I use to pass header values below

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:[self HTTPMethod]];
[request setHTTPBody:self.requestData];
[request addValue:@"xyz" forHTTPHeaderField:@"username"];
[request addValue:@"xyz" forHTTPHeaderField:@"password"];
[request addValue:[[NSUserDefaults standardUserDefaults]valueForKey:@"Auth"] forHTTPHeaderField:@"Authorization"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

I searched for header methods, But nothing helps.what I'm doing wrong here.pls anybody help me fix it.Thanks.


回答1:


Use setValue for request instead of addValue because with addValue If a value was previously set for the specified field, the supplied value is appended to the existing value using the appropriate field delimiter

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:[self HTTPMethod]];
[request setHTTPBody:self.requestData];
[request setValue:@"xyz" forHTTPHeaderField:@"username"];
[request setValue:@"xyz" forHTTPHeaderField:@"password"];
[request setValue:[[NSUserDefaults standardUserDefaults]valueForKey:@"Auth"] forHTTPHeaderField:@"Authorization"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

check apple documentation-

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableURLRequest_Class/#//apple_ref/occ/instm/NSMutableURLRequest/setValue:forHTTPHeaderField



来源:https://stackoverflow.com/questions/33537381/how-to-pass-authorization-token-header-objective-c

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