IOS中的HTTPS发布请求

时间:2013-06-04 13:07:47

标签: ios objective-c

我尝试使用以下代码发布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];

但是我得到了回应。

  

错误错误Domain = NSURLErrorDomain Code = -1202“此服务器的证书无效。您可能正在连接到假装为”portkey.formspring.me“的服务器,这可能会使您的机密信息面临风险。” UserInfo = 0x7564180 {NSLocalizedRecoverySuggestion =您是否要连接到服务器?,NSErrorFailingURLKey = https://portkey.formspring.me/login/,NSLocalizedDescription =此服务器的证书无效。您可能正在连接到假装>为“portkey.formspring.me”的服务器,这可能会使您的机密信息面临风险。,NSUnderlyingError = 0x7168a20“此服务器的证书无效。您可能正在连接到服务器这假装是“portkey.formspring.me”,可能会使您的机密信息面临风险。“,NSURLErrorFailingURLPeerTrustErrorKey =}

有人可以告诉我如何使用NSURLConnection发布帖子请求吗?

提前致谢。

2 个答案:

答案 0 :(得分:7)

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

默认情况下,iOS不允许您连接到提供不受信任证书的网站。如果绝对必要,您可以绕过此检查 - 请参阅此问题:How to use NSURLConnection to connect with SSL for an untrusted cert?

然而,实际修复相关证书会更好,更好。

答案 1 :(得分:0)

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