我正在为API调用传递用户名,密码,它返回正确的值。但是在身份验证API返回一个安全令牌之后,我需要捕获令牌并传递用户名和密码。我也是这样做但它返回禁止的错误,这表示无效的令牌错误。我也尝试了base64来传递令牌在stackoverflow中回答。我用来传递下面的标题值的代码
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"];
我搜索了标题方法,但没有任何帮助。我在这里做错了。请任何人帮我修复它。谢谢。
答案 0 :(得分:4)
使用setValue
代替addValue
,因为addValue
如果先前为指定字段设置了值,则使用相应的字段分隔符将提供的值附加到现有值
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"];
检查苹果文档 -