通过SSL请求Web服务

Str*_*boy 8 objective-c nsmutableurlrequest ios ios6

我正在努力使用https请求Web服务.我收到这样的错误:

An error occured : The certificate for this server is invalid. You might be connecting to a server that is pretending to be “SERVER_ADDRESS” which could put your confidential information at risk.
Run Code Online (Sandbox Code Playgroud)

我没有使用NSUrlConnectionDelegate.这是我的方法:

- (void)sendRequestWithUrl:(NSURL*)url block:(void (^)(NSDictionary *dict, NSError *error)) block{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    NSError* err = nil;
    NSHTTPURLResponse* rsp = nil;
    // Perform the request synchronously on this thread
    NSData *rspData = [NSURLConnection sendSynchronousRequest:request returningResponse:&rsp error:&err];
    if (rspData && err == nil) {
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:rspData options:NSJSONReadingMutableLeaves error:&err];
        if(result) {
            block(result, err);
        } else {
            block(nil, err);
        }
    }else{
        DLog(@"Requesting URL: %@  An error occured : %@",url,[err localizedDescription]);
        block(nil, err);
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎么能解决这个问题?

Apu*_*urv 1

您应该将以下委托方法添加到您的通信类中。

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
    {
        if ([YOUR_HOST isEqualToString:challenge.protectionSpace.host])
        {
            [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];           
        }
    }   
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
Run Code Online (Sandbox Code Playgroud)