<分区>
标签 ios objective-c http rest header
<分区>
我是 HTTP 的新手,因为传统上我只是一名前端开发人员,但根据我当前的契约(Contract),我被要求使用 REST API 从服务器提取数据。我需要使用 API key 和 API 用户名在 HTTP header 中对自己进行身份验证,根据 API 文档,我被要求在“ token ” header 中这样做。
关于如何格式化 NSURLRequest
以完成此任务,我可以获得任何帮助吗?我完全迷失在这里。
这是我引用的 API 文档的特定部分:
REST-APIUser—Token
The APIKey and APIUserName associated with the account have to be set to “REST-APIUser--Token” in Base64String Format in the token header as illustrated below: Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}",APIKey,APIUserName)))
Where,
APIKey – The Unique key associated with an API account
APIUserName – The UserName associated with an API account
APP-User-ID
ID of the currently logged in User has to be set to “APP-User-ID” in Base64String Format in the header. Convert.ToBase64String(Encoding.UTF8.GetBytes(AppUserID))
Where,
AppUserID – The User ID associated with the API application user
我拥有 {APIKey}、{APIUserName} 和 {AppUserID}。
最佳答案
参见 Add HTTP Header to NSURLRequest
/* Create request variable containing our immutable request
* This could also be a paramter of your method */
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.stackoverflow.com"]];
// Create a mutable copy of the immutable request and add more headers
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[mutableRequest addValue:@"__usersKey__" forHTTPHeaderField:@"token"];
// Now set our request variable with an (immutable) copy of the altered request
request = [mutableRequest copy];
// Log the output to make sure our new headers are there
NSLog(@"%@", request.allHTTPHeaderFields);
请注意,如果您指的是 HTTPS,则连接是需要身份验证的连接,而不是请求;尽管您似乎没有使用 HTTPS。
NSString* AppUserId = Convert.ToBase64String(Encoding.UTF8.GetBytes(AppUserID))//或者不管你需要什么功能,这看起来不像 Objective-C。
看How to Base64 encoding on the iPhone或类似的 base64。此贴建议https://github.com/nicklockwood/Base64/
如果使用那个库,你需要类似函数的东西
- (NSString *)base64EncodedString;
并向其传递您的 API 文档中描述的信息。我们无法为您提供更多帮助,因为我们没有您的所有信息。
例如,您可能想要:
NSString *token = [NSString stringWithFormat@"%@:%@",APIKey,APIUserName]
NSString *token64 = [token base64EncodedString]; //Assuming that's how you call the library's function. I have never used it so I don't know if it modifies NSString or what. You can always write a function for this part.
[mutableRequest addValue:@"APIUser--Token" forHTTPHeaderField:token64]; //Not sure what the API says the value should be, formatting isn't clear
//Follow the same lines for NSString *AppUserId
[mutableRequest addValue:@"APP-User-ID" forHTTPHeaderField:AppUserId];
只需按照那里的 API 以相同的方式执行 token (以相同的方式生成 token )。
关于ios - 如何配置用于身份验证的 HTTP header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20531658/