2013-12-11 22 views
0

我是新來的使用HTTP,因爲我一直只是一個前端開發人員,但與我目前的合同,我被要求使用REST API從服務器拉數據。我需要使用API​​密鑰和API用戶名在HTTP標頭中對自己進行身份驗證,並根據API文檔要求在「令牌」標頭中執行此操作。如何配置HTTP頭進行身份驗證?

我可以通過如何格式化NSURLRequest來完成此任務獲得任何幫助嗎?我完全迷失在這裏。

這裏的API文檔,我引用的特定部分:

REST-APIUser令牌

與 帳戶相關聯的APIKey和APIUserName已經被設置爲「 REST-APIUser-令牌「在Base64String格式 在令牌頭中,如下圖所示: Convert.ToBas e64String(Encoding.UTF8.GetBytes(的String.Format( 「{0}:{1}」,APIKey,APIUserName)))

APIKey - 與API帳戶

相關聯的唯一密鑰

APIUserName - 與API的帳戶相關聯的用戶名

APP-用戶ID

在用戶當前登錄ID必須被設定爲「APP-User-ID「in Base64String標題中的格式。 Convert.ToBase64String(Encoding.UTF8.GetBytes(AppUserID))

AppUserID - 與API應用程序用戶相關聯的用戶ID

我擁有的一個{APIKey},{APIUserName}和一個{AppUserID}。

+1

你提到的API文檔是什麼意思? –

+0

@KaiHuppmann查看編輯的問題。 – amarkon

回答

0

NSMutableURLRequest開始,並使用addValue:forHTTPHeaderField:setAllHTTPHeaderFields:方法將字段添加到文檔中顯示的標頭名稱。

3

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 [email protected]"%@:%@",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從那裏做標記以同樣的方式(生成相同的方式令牌)。

+0

你能檢查我更新的問題並確保你的答案仍然符合API規範嗎?謝謝 – amarkon

+0

我似乎認爲它確實如此,你能否更具體地認爲它沒有?還是你有第二個問題是如何創建將傳遞給「forHTTPHeaderField:」的字符串? –

+0

我不確定如何創建將傳遞給「forHTTPHeaderField:」的字符串。 – amarkon

相關問題