iPhone:安全 restfull 服务器"此服务器的证书无效



我正在尝试使用安全的restful服务,该服务会产生错误

Error=Error Domain=NSURLErrorDomain Code=-1202"此服务器的证书无效。您可能正在连接一个伪装成"xxx.xxx.xxx.xxx"的服务器,这可能会使您的机密信息面临风险。"

在xCode 4.2上工作,哪里有错误或缺少任何步骤。

使用以下代码

的注册用户

@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];
}

我觉得这可能是因为DNS,比如你的服务器没有注册。

尝试使用这个进行开发:

创建一个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。

我尝试了几种方法,发现它与苹果开发者中心证书有关。升级您的设置,然后重试。我试过用iPad、iPhone 5和5S发布数据,但iPhone 4除外。当我在iPhone 4上更新了我的配置和安装时,现在就可以使用了。

最新更新