我对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有点新意,所以要善待:)
谢谢你的帮助.麦克风