在IOS中的HTTPS发布请求

我试图通过使用下面的代码使https发布请求。

NSURL *url = [NSURL URLWithString:@"https://portkey.formspring.me/login/"]; //initialize a request from url NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]]; //set http method [request setHTTPMethod:@"POST"]; //initialize a post data NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:@"username", @"username", @"password", @"password", nil]; NSError *error=nil; NSData* jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:NSJSONWritingPrettyPrinted error:&error]; [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; //set post data of request [request setHTTPBody:jsonData]; //initialize a connection from request NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; //start the connection [connection start]; 

但即时得到以下回应。

错误错误域= NSURLErrorDomain代码= -1202“这个服务器的证书是无效的,你可能连接到假装为”portkey.formspring.me“的服务器,这可能会把你的机密信息置于危险之中。 UserInfo = 0x7564180 {NSLocalizedRecoverySuggestion =你想连接到服务器?NSErrorFailingURLKey = https://portkey.formspring.me/login/,NSLocalizedDescription =这个服务器的证书是无效的。 您可能正在连接到假装成“portkey.formspring.me”的服务器,这可能会使您的机密信息处于危险之中,NSUnderlyingError = 0x7168a20“此服务器的证书无效。您可能正在连接到服务器假装是“portkey.formspring.me”这可能会使您的机密信息处于危险之中。“,NSURLErrorFailingURLPeerTrustErrorKey =}

任何人都可以告诉我如何使用NSURLConnection发布请求?

提前致谢。

您尝试连接的网站证书不可信(请尝试访问您在Chrome中发布的链接)。

默认情况下,iOS不会让您连接到提供不可信证书的网站。 你可以绕过这个检查,如果绝对必要的 – 看到这个问题: 如何使用NSURLConnection与SSL连接不信任的证书?

但是,要真正解决证书问题,要做得更好,更好。

这些NSURLConnection委托方法弃用

 -(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace -(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge -(void)connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 

您可以使用-connection:willSendRequestForAuthenticationChallenge:而不是这3个已弃用的方法

 -(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodServerTrust) { [[challenge sender] useCredential:[NSURLCredential credentialForTrust:[[challenge protectionSpace] serverTrust]] forAuthenticationChallenge:challenge]; } }