Objective-C SSL同步连接

Mik*_*ike 4 ssl objective-c synchronous nsurlconnection

我对Objective-C有点新,但遇到了一个我无法解决的问题,主要是因为我不确定我是否正确实现了解决方案.

我正在尝试使用同步连接连接到具有自签名证书的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];  

}
Run Code Online (Sandbox Code Playgroud)

到NSURLDelegate接受所有证书.当我使用以下内容连接到网站时:

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

它工作正常,我看到挑战被接受.但是,当我尝试使用同步连接进行连接时,我仍然会收到错误,并且当我输入日志记录时,我看不到调用挑战函数.

如何使用同步连接来使用质询方法?是否与委托有关: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"); 
Run Code Online (Sandbox Code Playgroud)

就像我提到的,我对目标C有点新意,所以要善待:)

谢谢你的帮助.麦克风

Dav*_*har 7

根据Apple文档(URL加载系统编程指南),不建议使用同步NSURLRequest方法,因为"因为它有严重的限制".似乎缺乏控制哪些证书可接受的能力是这些限制之一.

是的,你是对的,它是delegate:selfNSURLConnection设置上导致你的委托方法被调用.由于简单(或简单)同步sendSynchronousRequest:调用不提供指定委托的方法,因此不使用这些委托方法.

  • @Pria - 这就是重点:当你使用同步请求时,没有办法指定委托对象.异步请求如下所示:`[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]`和同步调用类似于`[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]`.请注意,`-sendSynchronousRequest:returningResponse:error:`方法没有`delegate:`参数.底线:如果您需要NSURLDelegate可以提供的自定义,则必须使用异步请求. (2认同)