2013-12-18 63 views
2

我使用HTTPS方案調用Web服務。要訪問Web服務,我需要一個用戶名和密碼。我實現了http基本認證。 我總是得到401錯誤,我確信用戶名和密碼是正確的。這裏是我使用的代碼(我在這裏看到這個代碼:How can I pass credentials while using NSURLSession)。建議?謝謝!NSURLSession,HTTP基本身份驗證和自簽名證書

NSURL *url = [NSURL URLWithString:@"http://myurl...."]; 

NSString *user = @"userna,e"; 
NSString *password = @"password"; 
NSURLCredential *defaultCredential = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistencePermanent]; 

NSString *host = [url host]; 
NSInteger port = [[url port] integerValue]; 
NSString *protocol = [url scheme]; 

NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:host port:port protocol:protocol realm:nil authenticationMethod:NSURLAuthenticationMethodHTTPBasic]; 

NSURLCredentialStorage *credentials = [NSURLCredentialStorage sharedCredentialStorage]; 
[credentials setDefaultCredential:defaultCredential forProtectionSpace:protectionSpace]; 

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 
[config setURLCredentialStorage:credentials]; 

NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; 
[[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    if (!error) { 
     NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response; 
     NSLog(@"%d", httpResp.statusCode); 
    } 

}] resume]; 

... 

// ONLY FOR SELF-SIGNED CERTIFICATE!!! DANGEROUS!! 
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler 
{ 
    NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; 
    completionHandler(NSURLSessionAuthChallengeUseCredential,credential); 
} 

回答

2

對於基本身份驗證我沒能獲得與文檔中描述的方式工作,但我可以做什麼文檔說不能做,直接在會話中設置的標題。

這是Swift版本。

let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration() 
    sessionConfig.HTTPAdditionalHeaders = ["Authorization":"Basic fjdslkfsdfk="] 

我想你也可以直接在請求上設置它們。 Obj-C相當於留給讀者作爲練習。

有一個good blog post here解釋如何使用憑證代理。

+0

當然,這是最簡單的解決方案,但它的工作原理:) 我的要求是更好地理解NSURLSession及其代表。反正 ,+1 –

+0

@FabioMignogna不夠公平。我可能會再次嘗試正確的方式進行工作和更新,但最近卻發現問題沒有解決。我不確定這些問題是否由於服務器不良(發送400而不是401)或者因爲在基本授權或其他方面沒有真正的挑戰。我已經添加了由其他人發佈的最新帖子的鏈接。 –

+0

「fjdslkfsdfk =」部分是如何計算的? – Michael