2

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

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

1 回答 1

2

对于基本身份验证,我没有设法使用文档描述的方式,但我可以完全按照文档所说的去做,并直接在会话中设置标题。

这是斯威夫特版本。

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

我认为您也可以直接在请求中设置它们。Obj-C 等价物留给读者作为练习。

这里有一篇很好的博客文章,解释了应该如何使用凭证委托。

于 2014-11-06T12:56:33.510 回答