3

我想知道是否有人可以帮助我了解如何将 SSL 证书处理添加到与 https 服务的同步连接中。

我知道如何使用异步连接而不是同步来做到这一点。

                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

谢谢你。

4

3 回答 3

7

使用静态 sendSynchronousRequest 函数是不可能的,但我找到了替代方法。

首先像这样的NSURLConnectionDataDelegate对象

FailCertificateDelegate.h

@interface FailCertificateDelegate : NSObject <NSURLConnectionDataDelegate>
   @property(atomic,retain)NSCondition *downloaded;
   @property(nonatomic,retain)NSData *dataDownloaded;
   -(NSData *)getData;
@end

FailCertificateDelegate.m

#import "FailCertificateDelegate.h"

@implementation FailCertificateDelegate
@synthesize dataDownloaded,downloaded;
-(id)init{
    self = [super init];
    if (self){
        dataDownloaded=nil;
        downloaded=[[NSCondition alloc] init];   
    }
    return self;
}


- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:    (NSURLProtectionSpace *)protectionSpace {
    NSLog(@"canAuthenticateAgainstProtectionSpace:");
    return [protectionSpace.authenticationMethod         isEqualToString:NSURLAuthenticationMethodServerTrust];
}


- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:    (NSURLAuthenticationChallenge *)challenge {
     NSLog(@"didReceiveAuthenticationChallenge:");
    [challenge.sender useCredential:[NSURLCredential     credentialForTrust:challenge.protectionSpace.serverTrust]     forAuthenticationChallenge:challenge];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [downloaded signal]; 
    [downloaded unlock];
    self.hasFinnishLoading = YES; 
} 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [dataDownloaded appendData:data];
    [downloaded lock]; 
} 

-(NSData *)getData{
    if (!self.hasFinnishLoading){
        [downloaded lock]; 
        [downloaded wait]; 
        [downloaded unlock]; 
    } 

    return dataDownloaded; 
}

@end

并使用它

FailCertificateDelegate *fcd=[[FailCertificateDelegate alloc] init];
NSURLConnection *c=[[NSURLConnection alloc] initWithRequest:request delegate:fcd startImmediately:NO];
[c setDelegateQueue:[[NSOperationQueue alloc] init]];
[c start];    
NSData *d=[fcd getData];

现在您将获得异步使用 nsurlconnection 的所有好处和简单同步连接的好处,线程将被阻塞,直到您下载委托上的所有数据,但您可以改进它,在 FailCertificateDelegate 类上添加一些错误控制

编辑:修复大数据。基于 Nikolay DS 的评论。非常感谢

于 2013-09-17T07:30:19.267 回答
-1

我有一个类似的问题。在我的情况下,我使用允许我接受任何证书的两个委托方法根据需要使用 ssl 进行异步连接:

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

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}

但我坚持以同步方式做同样的事情。我在网上搜索,直到找到您的帖子,不幸的是,另一个stackoverflow 帖子暗示您无法在 NSURLConnection 上执行同步调用并使用 ssl(因为缺少处理 ssl 身份验证过程的委托)。我最终做的是获取 ASIHTTPRequest 并使用它。这样做很轻松,我花了大约一个小时来设置它并且它工作得很好。这是我如何使用它。

+ (NSString *) getSynchronously:(NSDictionary *)parameters {
    NSURL *url = [NSURL URLWithString:@"https://localhost:8443/MyApp/";
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    NSString *parameterJSONString = [parameters JSONRepresentation];
    [request appendPostString:parameterJSONString];
    [request addRequestHeader:@"User-Agent" value:@"MyAgent"];
    request.timeOutSeconds = CONNECTION_TIME_OUT_INTERVAL;
    [request setValidatesSecureCertificate:NO];
    [request startSynchronous];

    NSString *responseString = [request responseString];
    if (request.error) {
        NSLog(@"Server connection failed: %@", [request.error localizedDescription]);
    } else {
        NSLog(@"Server response: %@", responseString);
    }

    return responseString;
}

当然,重要的部分是

[request setValidatesSecureCertificate:NO];

您的另一种选择是使用上述两种方法在具有异步连接的另一个线程中处理下载,并阻止您想要同步连接的线程,直到请求完成

于 2011-02-22T10:13:50.030 回答
-2

我接近使用下面的代码找到解决方案。这可行,但经常崩溃,可能是因为我在编写代码的方式上做错了,而且我对所使用的方法没有深入的了解。但是,如果有人对如何改进这一点有任何建议,请发布。

就在这一行之后:

NSError* myError;

就在该行之前:

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

添加:

    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];
于 2010-08-28T12:18:01.393 回答