最初使用SSL连接到REST API时,NSURLConnection加载有时会失败

时间:2015-03-30 20:58:02

标签: ios ssl nsurlconnection

我正在开发一个连接到REST API的iOS应用程序,最近希望它使用SSL进行连接,因此我更改了网址并添加了一些其他方法,以便能够。但是,它通常会在最初出错,然后就没有其他问题了。谁能在下面的代码中看到任何明显的错误?

以下是出现的错误: NSURLConnection / CFURLConnection HTTP加载失败(kCFStreamErrorDomainSSL,-9813)

代码如下:

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {

    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {

    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
            [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];

    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

- (void)load:(NSData*)data completionHandler:(void(^)(NSURLResponse *response, NSData *data, NSError *error))handler

{
    NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"Loading... %@", s);

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    [request setHTTPMethod:@"POST"];

    [request setHTTPBody:data];

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    [NSURLConnection sendAsynchronousRequest:request queue:queue

                           completionHandler:handler];

    [urlConnection start];
}

0 个答案:

没有答案