2010-04-21 20 views
4

我對Objective-C有點新,但遇到了一個我無法解決的問題,主要是因爲我不確定我是否正確實施解決方案。Objective-C SSL同步連接

我正在嘗試使用自簽名證書與https站點進行同步連接。我越來越

錯誤域= NSURLErrorDomain代碼= -1202「不受信任的服務器證書」

錯誤,我已經看到了一些解決方案,在這個論壇。我找到的解決方案是:

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace { 
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 
    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; 

} 

到NSURLDelegate接受所有證書。當我連接到該網站使用只是:

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://examplesite.com/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

它工作正常,我看到挑戰被接受。但是,當我嘗試使用同步連接進行連接時,我仍然收到錯誤信息,並且在登錄時看不到正在調用的挑戰函數。

如何獲得同步連接以使用挑戰方法?是否與代表有關:URLConnection的自我部分?我還記錄了在我的連接函數調用的NSURLDelegate內發送/接收數據,但不是由同步函數調用。

我使用的同步部分內容:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:@"https://examplesite.com/"]]; 
     [request setHTTPMethod: @"POST"]; 
     [request setHTTPBody: [[NSString stringWithString:@"username=mike"] dataUsingEncoding: NSUTF8StringEncoding]]; 
     dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
     NSLog(@"%@", error); 
     stringReply = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding]; 
     NSLog(@"%@", stringReply); 
     [stringReply release]; 
     NSLog(@"Done"); 

就像我提到我有點新目標C所以任何幫助:)種類

感謝。 Mike

+0

您是否最終將您的請求轉換爲異步?我遇到了同樣的問題,並且不得不轉換我的代碼做惡夢。 – kmehta 2011-05-11 22:36:39

回答

7

根據Apple文檔(URL Loading System Programming Guide),不推薦使用同步NSURLRequest方法,因爲「因爲它有嚴格的限制」。似乎缺乏控制可接受的證書的能力是這些限制之一。

是的,你是對的,在NSURLConnection設置,導致你的委託方法被調用。由於簡單(或過分簡化)的同步調用沒有提供指定委託的方式,因此不使用這些委託方法。

+0

我在哪裏可以從同步請求中調用委託:self? – Pria 2010-09-29 11:21:15

+2

@Pria - 這就是要點:當你使用同步請求時,沒有辦法指定一個委託對象。一個異步請求看起來像:'[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]',同步調用就像'[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]'。請注意,'-sendSynchronousRequest:returningResponse:error:'方法沒有'delegate:'參數。底線:如果您需要NSURLDelegate可以提供的定製,則必須使用異步請求。 – 2010-09-29 12:51:42

+0

非常感謝..! – Pria 2010-10-01 06:25:59