2013-12-18 64 views
2

我使用HTTPS方案调用Web服务。要访问Web服务,我需要一个用户名和密码。我实现了http基本认证。 我总是得到401错误,我确信用户名和密码是正确的。这里是我使用的代码(我在这里看到这个代码:How can I pass credentials while using NSURLSession)。建议?谢谢!NSURLSession,HTTP基本身份验证和自签名证书

NSURL *url = [NSURL URLWithString:@"http://myurl...."]; 

NSString *user = @"userna,e"; 
NSString *password = @"password"; 
NSURLCredential *defaultCredential = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistencePermanent]; 

NSString *host = [url host]; 
NSInteger port = [[url port] integerValue]; 
NSString *protocol = [url scheme]; 

NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:host port:port protocol:protocol realm:nil authenticationMethod:NSURLAuthenticationMethodHTTPBasic]; 

NSURLCredentialStorage *credentials = [NSURLCredentialStorage sharedCredentialStorage]; 
[credentials setDefaultCredential:defaultCredential forProtectionSpace:protectionSpace]; 

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 
[config setURLCredentialStorage:credentials]; 

NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; 
[[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    if (!error) { 
     NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response; 
     NSLog(@"%d", httpResp.statusCode); 
    } 

}] resume]; 

... 

// ONLY FOR SELF-SIGNED CERTIFICATE!!! DANGEROUS!! 
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler 
{ 
    NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; 
    completionHandler(NSURLSessionAuthChallengeUseCredential,credential); 
} 

回答

2

对于基本身份验证我没能获得与文档中描述的方式工作,但我可以做什么文档说不能做,直接在会话中设置的标题。

这是Swift版本。

let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration() 
    sessionConfig.HTTPAdditionalHeaders = ["Authorization":"Basic fjdslkfsdfk="] 

我想你也可以直接在请求上设置它们。 Obj-C相当于留给读者作为练习。

有一个good blog post here解释如何使用凭证代理。

+0

当然,这是最简单的解决方案,但它的工作原理:) 我的要求是更好地理解NSURLSession及其代表。反正 ,+1 –

+0

@FabioMignogna不够公平。我可能会再次尝试正确的方式进行工作和更新,但最近却发现问题没有解决。我不确定这些问题是否由于服务器不良(发送400而不是401)或者因为在基本授权或其他方面没有真正的挑战。我已经添加了由其他人发布的最新帖子的链接。 –

+0

“fjdslkfsdfk =”部分是如何计算的? – Michael