我对 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];
}
到 NSURLDelegate 接受所有证书。当我仅使用以下命令连接到该站点时:
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://examplesite.com/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
它工作正常,我看到挑战被接受。但是,当我尝试使用同步连接进行连接时,我仍然会收到错误消息,并且在输入日志记录时没有看到调用的质询函数。
如何获得同步连接以使用挑战方法?它与 URLConnection 的 delegate:self 部分有关吗?我还记录了 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 有点陌生,所以请善待 :)
谢谢你的帮助。麦克风