views:

30

answers:

1

Hi,

I was wondering if anyone can help me understand how to add SSL certificate handling to synchronous connections to a https service.

I know how to do this with asynchronous connections but not synchronous.

                NSString *URLpath = @"https://mydomain.com/";
    NSURL *myURL = [[NSURL alloc] initWithString:URLpath];
    NSMutableURLRequest *myURLRequest = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
    [myURL release];
    [myURLRequest setHTTPMethod:@"POST"];

    NSString *httpBodystr = @"setting1=1";
    [myURLRequest setHTTPBody:[httpBodystr dataUsingEncoding:NSUTF8StringEncoding]];

    NSHTTPURLResponse* myURLResponse; 
    NSError* myError;
    NSData* myDataResult = [NSURLConnection sendSynchronousRequest:myURLRequest returningResponse:&myURLResponse error:&myError];

            //I guess I am meant to put some SSL handling code here

Thank you.

A: 

Im close to finding the solution for this with the code below. This works but often crashes probably because I am doing something wrong in the way I code this and I don't have a strong understanding of the methods used. But if anyone has any suggestions on how to improve this than please post.

Just after the line:

NSError* myError;

and just before the line:

NSData* myDataResult = [NSURLConnection sendSynchronousRequest:myURLRequest       
returningResponse:&myURLResponse error:&myError];

add:

    int failureCount = 0;
    NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]      
    initWithHost:@"mydomain.com" port:443 protocol:@"https"  realm:nil  
    authenticationMethod:NSURLAuthenticationMethodServerTrust];

    NSURLResponse *response = [[NSURLResponse alloc] initWithURL:myURL MIMEType:@"text/html" 
    expectedContentLength:-1 textEncodingName:nil]; 

    NSURLAuthenticationChallenge *challange = [[NSURLAuthenticationChallenge alloc] 
    initWithProtectionSpace:protectionSpace proposedCredential:[NSURLCredential 
    credentialForTrust:protectionSpace.serverTrust] previousFailureCount:failureCount 
    failureResponse:response error:myError sender:nil];