使用同步请求时NSURLErrorDomain Code = -1202

时间:2013-12-31 14:36:34

标签: ios objective-c nsurlconnection nsurlrequest nsurlerrordomain

我尝试发送同步请求并得到以下错误。

  

错误域= NSURLErrorDomain代码= -1202“此证书   服务器无效。您可能正在连接到的服务器   假装是“xx.xxxx.com”,可以保密   有风险的信息。“

请找到以下代码

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

以上两种方法都没有被调用,在我的情况下我只需要发送同步请求。

我使用了下面一行,但它运行正常,但AppStore拒绝了我的应用程序:

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

要么使用NSURLConnection方法的异步版本(允许您指定委托),要么使用trick like this来处理异步调用,就好像它是同步调用一样。

编辑:

关于使用NSURLConnection的异步版本,我的意思是:

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

(您需要具有NSURLConnection *强属性)。