NSURLErrorDomain Code=-1202 when using Syncronous request

4.6k views Asked by At

I try to send the synchronous request and got the below error.

Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “xx.xxxx.com” which could put your confidential information at risk."

Please find the code below

    NSURL *url=[[NSURL alloc]initWithString:strURL];
        NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url];
        [url release];
        [request setTimeoutInterval:90];
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody:dataForChallenge];
        [request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

        NSURLResponse *resp = nil;
        NSError *err = nil;
        NSData *response = [NSURLConnection sendSynchronousRequest: request returningResponse: &resp error: &err];


    - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    //    NSLog(@"selector : %@",NSStringFromSelector(_cmd));
    if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
    {
        //      NSLog(@"selector 1: %@",NSStringFromSelector(_cmd));
        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
    }
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    //    NSLog(@"selector : %@",NSStringFromSelector(_cmd));    
    if( [[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust] )
    {
        //      NSLog(@"selector 1: %@",NSStringFromSelector(_cmd));    
        return YES;
    }
    return NO;
}

The above two methods are not getting called, in my case i have to send Synchronous request only.

I used the below line and it works fine but AppStore rejected my App:

    [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

How can i fix this?

1

There are 1 answers

2
sergio On

Either you use the asynchronous version of NSURLConnection methods (which allow you to specify a delegate) or you use a trick like this to handle an async call as if it were a sync call.

EDIT:

about using the async version of NSURLConnection, what I meant is:

self.connection = [[NSURLConnection alloc] initWithRequest:request
                                 delegate:self];

(You will need to have a NSURLConnection* strong property).