我正在尝试使用提供错误的安全宁静服务
错误=错误域= NSURLErrorDomain代码= -1202“此服务器的证书无效。您可能正在连接到假装为“ xxx.xxx.xxx.xxx”的服务器,这可能会将您的机密信息处于危险之中。“
在xCode 4.2上工作,哪里有错误或缺少任何步骤。
使用以下代码
RegisterUser.f
@interface RegisterUser : UIViewController<UITextFieldDelegate,
UIScrollViewDelegate, NSURLConnectionDelegate>
RegisterUser.m
- (IBAction)SubmitBtnAction:(id)sender {
NSURL *url = [NSURL URLWithString:@"https://xx.xx.xx.xxx:8223/jaxrs/tunedoorgateway/getCountries"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] >0 && error == nil)
{
NSLog(@"Data = %@", data);
// DO YOUR WORK HERE
}
else if ([data length] == 0 && error == nil)
{
NSLog(@"Nothing was downloaded.");
}
else if (error != nil){
NSLog(@"Error = %@", error);
}
}];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
NSLog(@"This is canAuthenticateAgainstProtectionSpace");
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
// if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
// if ([trustedHosts containsObject:challenge.protectionSpace.host])
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
NSLog(@"This is didReceiveAuthenticationChallenge");
// [[challenge sender] cancelAuthenticationChallenge:challenge];
}
尝试将其用于开发:
创建NSURLRequest+NSURLRequestSSLY.h
文件并向其中添加这些行
#import <Foundation/Foundation.h>
@interface NSURLRequest (NSURLRequestSSLY)
+(BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
@end
创建NSURLRequest+NSURLRequestSSLY.m
文件并向其中添加这些行
#import "NSURLRequest+NSURLRequestSSLY.h" @implementation NSURLRequest (NSURLRequestSSLY) +(BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host { return YES; } @end
并且不要忘记在发布之前将其删除,因为您的应用可能会被拒绝。
HTTPS服务器。如果您自行设置服务器,则必须从iOS和大多数其他操作系统信任的大型证书颁发机构之一购买一份证书。
出于开发目的,您可以通过忽略不受信任的证书来测试REST服务。请按照此指南进行操作:http://www.cocoanetics.com/2009/11/ignoring-certificate-errors-on-nsurlrequest/但是对于生产用途,我建议您不要使用此方法,因为它会给您的应用程序带来安全漏洞。如果您确实忽略了安全性,那么也可以仅使用HTTP代替HTTPS。