我有一个连接到我的家庭路由器网络界面的应用程序。我想将其转换为使用 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 无法验证身份....我必须单击继续继续。 我怎样才能做到这一点?不幸的是,我对 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];
最佳答案
要绕过主机证书的有效性检查,请添加以下代码。
首先为 SDK 中已有但未公开的 setter 方法添加一个接口(interface):
@interface NSURLRequest(Private)
+(void)setAllowsAnyHTTPSCertificate:(BOOL)inAllow forHost:(NSString *)inHost;
@end
现在,每当您呈现新请求时,调用该 setter :
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[inURL host]];
警告
请勿将此代码用于生产,而只能在证书尚未批准/提交/安装的情况下开发您的应用程序时使用。典型的是使用未安装受信任证书的开发服务器。 使用此代码将使您的应用程序拒绝通过 iTunes 分发,因为它使用私有(private) API 方法。
为确保在生产环境中顺利运行,您必须为您的主机获取受信任的 SSL 证书。有各种权威公司提供这样的东西。至少要提到一个(还有很多),您可以使用 GoDaddy .
更新(2013 年 5 月 31 日)
AFNetworking got updated支持开箱即用的无效证书,无需使用任何私有(private) API。感谢 Peter Steinberger!
要启用该功能,最方便的解决方案是将以下内容添加到您的前缀 header (.pch):
#ifdef DEBUG
#define _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
#endif
再一次强调,您应该避免在生产代码中启用该功能 - 您几乎会使整个 SSL 连接点无效并使它们容易受到攻击。
关于ios - 从 http 切换到 https。证书无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12447318/