从http切换到https。 无效的证书

我有一个应用程序,连接到我的家庭路由器的Web界面。 我想转换这个使用https而不是只是http。 我最初使用ASIHttpRequest ,但因为它不再支持我切换到AFNetworking 。 问题是,每当我尝试连接,我得到这个错误消息:

 _block_invoke_0220 [Line 243] ERROR: Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “192.168.1.1” which could put your confidential information at risk." UserInfo=0x9792ad0 {NSErrorFailingURLStringKey=https://192.168.1.1/Info.live.htm, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSErrorFailingURLKey=https://192.168.1.1/Info.live.htm, NSLocalizedDescription=The certificate for this server is invalid. You might be connecting to a server that is pretending to be “192.168.1.1” which could put your confidential information at risk., NSUnderlyingError=0xa6a3560 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “192.168.1.1” which could put your confidential information at risk.", NSURLErrorFailingURLPeerTrustErrorKey=< SecTrustRef: 

如果我导航到我Safari浏览器的url,我得到一个消息,Safari不能validation身份….我必须点击继续进行。 我怎样才能做到这一点? 对于ssl或https,我不太了解。 这是我目前使用的代码:

 NSString *urlString = @"https://192.168.1.1/"; NSURL *url = [NSURL URLWithString:urlString]; // Set authorization AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; [httpClient setAuthorizationHeaderWithUsername:user password:pass]; NSURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"Info.live.htm" parameters:nil]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSString *responceString = [operation responseString]; // NSLog(@"%@",responceString); if ([self parseInfoLive:responceString]) [[NSNotificationCenter defaultCenter] postNotificationName:@"downloadsComplete" object:nil]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"ERROR: %@",error.description); }]; [operation start]; 

为了绕过主机证书的有效性检查,添加下面的代码。

首先为setter方法添加一个接口,这个接口已经在SDK中但是不公开:

 @interface NSURLRequest(Private) +(void)setAllowsAnyHTTPSCertificate:(BOOL)inAllow forHost:(NSString *)inHost; @end 

现在,无论何时你正在渲染一个新的请求,调用setter:

 [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[inURL host]]; 

警告

不要将此代码用于生产,而只能在证书尚未被批准/提交/安装的情况下开发您的应用程序。 典型的是使用没有安装可信证书的开发服务器。 此代码的使用将使您的应用程序通过iTunes分发被拒绝,因为它使用私有API方法。

为了确保在生产环境中工作顺利,您必须为您的主机获得可信的SSL证书。 有各种权威的公司提供这样的事情。 至less要提到一个(还有很多),你可以使用GoDaddy 。


更新(2013年5月31日)

AFNetworking得到更新 ,支持无效的证书,不使用任何私人API。 荣誉彼得·斯坦伯格!

为了启用该function,最方便的解决scheme是将以下内容添加到您的前缀头文件(.pch)中:

 #ifdef DEBUG #define _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ #endif 

再一次,我不能强调足够的,你应该避免在生产代码中启用该function – 你几乎使SSL连接的整个点无效,并使其易受攻击。

Apple文档中的这个URL可能有助于检查这个链接

在上面的文件中读取简介部分。 Apple文档的屏幕截图

我不熟悉AFNetworking,但是这里有一个解决scheme可以解决你所看到的错误。 直到答案被誉为让你不能提交你的应用程序到应用程序商店。