附带认证要求的服务无法成功获取Json   http://stackoverflow.com/questions/33108166/nsurlsession-and-authentication-with-credentials
遇到同样问题.https://bookapi.bignerdranch.com/private/courses.json
自己输入账号密码可以看到Json
使用代理方法返回 HTTP Basic: Access denied.NSURLSessionDelegate-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{
    NSURLCredential *cred = [NSURLCredential credentialWithUser:@"BigNerdRanch" password:@"AchieveNerdvana" persistence:NSURLCredentialPersistencePermanent];
    completionHandler(NSURLSessionAuthChallengeUseCredential,cred);
}先行谢过

解决方案 »

  1.   

    如果用的是NSURLSession-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
    completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
    {
        NSString *authMethod = [[challenge protectionSpace] authenticationMethod];
        
        if ([authMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
            
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
        } else {
            NSURLCredential *cred = [NSURLCredential credentialWithUser:self.username
                                                               password:self.password
                                                            persistence:NSURLCredentialPersistenceNone];
            [[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
            completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
        }
    }
    如果是NSURLConnection- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
        if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
        } else {
            if ([challenge previousFailureCount] == 0) {
                if (self.credential) {
                    [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge];
                } else {
                    [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
                }
            } else {
                [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
            }
        }
    }
    希望对你有帮助
      

  2.   


    -(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
    completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
    {
        NSString *authMethod = [[challenge protectionSpace] authenticationMethod];
        
        if ([authMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
            
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
        } else {
            NSURLCredential *cred = [NSURLCredential credentialWithUser:@"BigNerdRanch"
                                                               password:@"AchieveNerdvana"
                                                            persistence:NSURLCredentialPersistenceNone];
            [[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
            completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
        }
    }测试无效.链接和密码确实是对的.
      

  3.   

    试试这个,亲测有效- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
     completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler
    {
        NSLog(@"did receive challenge method called with task");
        NSString* username = @"BigNerdRanch";
        NSString* password = @"AchieveNerdvana";
        
        
        NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
        __block NSURLCredential *credential = nil;
        
        credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
        
        if( completionHandler )
        {
            completionHandler(disposition, credential);
        }
    }返回--block 回调数据---3593字符:
    {"courses":[{"title":"iOS Essentials with Swift","url":"https://training.bignerdranch.com/classes/ios-essentials-with-swift","upcoming":[{"start_date":"2017-04-01","end_date":"2017-04-07","instructors":"Scott Ritchie","location":"Big Nerd Ranch West"},{"start_date":"2017-05-20","end_date":"2017-05-26","instructors":"Scott Ritchie","location":"Big Nerd Ranch West"},{"start_date":"2017-06-17","end_date":"2017-06-23","instructors":"Joseph Dixon","location":"Big Nerd Ranch Stone Mountain"},{"start_date":"2017-07-15","end_date":"2017-07-21","instructors":"Scott Ritchie","location":"Big Nerd Ranch West"},{"start_date":"2017-08-12","end_date":"2017-08-18","instructors":"Scott Ritchie","location":"Big Nerd Ranch West"},{"start_date":"2017-09-09","end_date":"2017-09-15","instructors":"Bolot Kerimbaev","location":"Big Nerd Ranch Stone Mountain"},{"start_date":"2017-10-07","end_date":"2017-10-13","instructors":"Scott Ritchie","location":"Big Nerd Ranch West"},{"start_date":"2017-11-04","end_date":"2017-11-10","instructors":"Scott Ritchie","location":"Big Nerd Ranch West"},{"start_date":"2017-12-09","end_date":"2017-12-15","instructors":"Scott Ritchie","location":"Big Nerd Ranch West"}]},{"title":"Accelerated iOS with Swift","url":"https://training.bignerdranch.com/classes/accelerated-ios-with-swift","upcoming":[{"start_date":"2017-04-24","end_date":"2017-04-28","instructors":"Scott Ritchie","location":"Big Nerd Ranch West"},{"start_date":"2017-08-28","end_date":"2017-09-01","instructors":"Scott Ritchie","location":"Big Nerd Ranch West"},{"start_date":"2017-10-23","end_date":"2017-10-27","instructors":"Joseph Dixon","location":"Big Nerd Ranch Stone Mountain"}]},{"title":"Advanced iOS Bootcamp","url":"https://training.bignerdranch.com/classes/advanced-ios-bootcamp","upcoming":[{"start_date":"2017-05-01","end_date":"2017-05-05","instructors":"Mikey Ward","location":"Big Nerd Ranch Stone Mountain"},{"start_date":"2017-07-17","end_date":"2017-07-21","instructors":"Mikey Ward","location":"Big Nerd Ranch Stone Mountain"},{"start_date":"2017-09-18","end_date":"2017-09-22","instructors":"Mikey Ward","location":"Big Nerd Ranch West"},{"start_date":"2017-12-04","end_date":"2017-12-08","instructors":"Mikey Ward","location":"Big Nerd Ranch West"}]},{"title":"Android Essentials","url":"https://training.bignerdranch.com/classes/android-essentials","upcoming":[{"start_date":"2017-03-06","end_date":"2017-03-10","instructors":"Paul Turner","location":"Big Nerd Ranch West"},{"start_date":"2017-05-15","end_date":"2017-05-19","instructors":"Brian Gardner","location":"Big Nerd Ranch Stone Mountain"},{"start_date":"2017-08-21","end_date":"2017-08-25","instructors":"David Greenhalgh","location":"Big Nerd Ranch Stone Mountain"},{"start_date":"2017-12-04","end_date":"2017-12-08","instructors":"David Greenhalgh","location":"Big Nerd Ranch Stone Mountain"}]},{"title":"Advanced Android","url":"https://training.bignerdranch.com/classes/advanced-android","upcoming":[{"start_date":"2017-04-24","end_date":"2017-04-28","instructors":"Brian Gardner","location":"Big Nerd Ranch Stone Mountain"},{"start_date":"2017-10-16","end_date":"2017-10-20","instructors":"David Greenhalgh","location":"Big Nerd Ranch West"}]},{"title":"Front-End Essentials","url":"https://training.bignerdranch.com/classes/front-end-essentials","upcoming":[{"start_date":"2017-08-14","end_date":"2017-08-18","instructors":"Jonathan Martin","location":"Big Nerd Ranch Stone Mountain"},{"start_date":"2017-10-23","end_date":"2017-10-27","instructors":"Chris Aquino","location":"Big Nerd Ranch Stone Mountain"}]}]}
      

  4.   


    奇怪还是无效.
    NSString *requestString = @"http://bookapi.bignerdranch.com/courses.json";不用验证的链接可以获取
    能提供些思路或者源码么
    2017-02-28 20:05:06.321 Nerdfeed[30886:3979005] did receive challenge method called with task
    2017-02-28 20:05:07.216 Nerdfeed[30886:3979005] HTTP Basic: Access denied.
      

  5.   

    这是完整的请求,你试试- (void) get
    {
        NSMutableString * url = [NSMutableString string];
        [url appendString:@"https://bookapi.bignerdranch.com/private/courses.json"];
        
        NSString *authStr = [NSString stringWithFormat:@"%@:%@", @"BigNerdRanch", @"AchieveNerdvana"];
        NSString *base64String = [[authStr dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
        NSString *authValue = [NSString stringWithFormat:@"Basic %@", base64String];
        NSDictionary *headers = @{ @"authorization": authValue,
                                   @"accept": @"application/json",
                                   @"accept": @"text/html",
                                   @"cache-control": @"no-cache",
                                   @"postman-token": @"0a47efb3-c559-c0f9-8276-87cbdbe76c9d" };
        
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setHTTPMethod:@"GET"];
        [request setURL:[NSURL URLWithString:url]];
        [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
        [request setTimeoutInterval:10];
        [request setHTTPShouldHandleCookies:FALSE];
        [request setAllHTTPHeaderFields:headers];
        
        NSOperationQueue *queue = [NSOperationQueue mainQueue];
        NSURLSessionConfiguration * defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession * session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:queue];
        NSURLSessionTask *task = [session dataTaskWithRequest:request];
        [task resume];
    }
      

  6.   


    已经成功!!
    非常感谢你的大力相助.
    经测试
    使用NSMutableURLRequest,以及进行对header的设置.是带验证服务通过的关键.
    /
    NSString *authStr = [NSString stringWithFormat:@"%@:%@", @"BigNerdRanch", @"AchieveNerdvana"];
    NSString *base64String = [[authStr dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
    NSString *authValue = [NSString stringWithFormat:@"Basic %@", base64String];
    NSDictionary *headers1 = @{ @"authorization": authValue};
     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setAllHTTPHeaderFields:headers];//另外没有添加setTimeoutInterval,因为有可能超时失败
    //[request setTimeoutInterval:10]
    私信您求个联系方法.
    再次感谢你的回答.