2016-09-04 4 views
0

Ich suchte alle verfügbaren Lösung Stackoverflow. Immer noch damit verwechselt.
Bitte zeigen Sie mir, wenn ich einen Fehler mache. Ich bekomme 401 Fehler.NSURLSession Mit Basic Authentication Challenge

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL  URLWithString:@"http://qa.api.xxxxxx.com/v0/jobs/93033"]]; 
NSString *authStr = @"xxxxxxxx:xxxxxxxxxxx"; 
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding]; 
NSString *authValue = [NSString stringWithFormat:@"Basic %@",[authData base64EncodedStringWithOptions:0]]; 
[request setValue:authValue forHTTPHeaderField:@"Authorization"]; 
request.HTTPMethod = @"GET"; 
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
//create the task 
NSURLSessionDataTask* task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 
    if (httpResponse.statusCode == 200) 
    { 
     NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
     NSLog(@"%@",json); 
     dispatch_async(dispatch_get_main_queue(), ^{ 
     }); 
    } else { 
     // failure: do something else on failure 
     NSLog(@"httpResponse code: %@", [NSString stringWithFormat:@"%ld", (unsigned long)httpResponse.statusCode]); 
     NSLog(@"httpResponse head: %@", httpResponse.allHeaderFields); 
     return; 
    } 

}]; 

[task resume]; 
+0

Möglicherweise möchten Sie Ihre API-Schlüssel aus der Frage entfernen – Tibrogargan

+0

Vielen Dank. Aber gut. Ich habe es in PostMan versucht, es funktioniert gut. Ich denke wirklich, warum es nicht funktioniert. –

Antwort

0

Vielleicht ist Ihr Ausgang AuthValue enthält neue Linien nach base64 tun, versuchen Sie die Zeichenfolge zu protokollieren und neue Linien zu entfernen, sonst wird der Header nicht gesetzt werden.

0

Mit dem Ansatz didReceiveAuthenticationChallenge können Sie die grundlegende Autorisierung in iOS verwenden.

Anfrage:

NSURL *URL = [NSURL URLWithString:@"http://qa.api.freshersworld.com/v0/jobs/93033"]; 
NSURLRequest *request = [NSURLRequest requestWithURL:URL 
              cachePolicy:NSURLRequestUseProtocolCachePolicy 
             timeoutInterval:30.0]; 

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

Delegierten:

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 
     if ([challenge previousFailureCount] == 0) { 
     NSLog(@"received and handle authentication challenge"); 
     NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"xxxx" 
                    password:@"xxxx" 
                   persistence:NSURLCredentialPersistenceForSession]; 
     [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge]; 
    } 
    else { 
     NSLog(@"previous authentication failure"); 
    } 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
     NSLog(@"%@", response); 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
     NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
     NSLog(@"%@", responseString); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
     NSLog(@"%@", error); 
} 
1

Vielleicht Ihre Anfrage an einige umgeleitet wird, wo sonst mit einer neuen Anforderung, die automatisch generiert wird durch NSURLSession unbefugt-Header.

Sie könnten Wireshark verwenden, um Ihre Anfrage genau passiert zu verfolgen.

Wenn Ihre Anfrage weitergeleitet wird, können Sie die folgenden Methoden verwenden, um sicherzustellen, dass die neue Anforderung mit Authentifizierungsinformationen sendet:

1. Verwenden Sie delegierte Methode zum Umgang mit Authentifizierung

- (void)URLSession:(NSURLSession *)session 
       task:(NSURLSessionTask *)task 
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge 
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler { 
    if (challenge.previousFailureCount > 1) { 
     completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); 
    }else { 
     NSURLCredential *credential = [NSURLCredential credentialWithUser:@"user" 
                   password:@"pswd" 
                   persistence:NSURLCredentialPersistenceForSession]; 
     completionHandler(NSURLSessionAuthChallengeUseCredential, credential); 
    } 
} 

Sollte der beste Weg, um Authentifizierungen zu behandeln.

2. Verwenden Delegate Methode hinzufügen Authentication Header nach New Anfrage

- (void)URLSession:(NSURLSession *)session 
       task:(NSURLSessionTask *)task 
willPerformHTTPRedirection:(NSHTTPURLResponse *)response 
     newRequest:(NSURLRequest *)request 
completionHandler:(void (^)(NSURLRequest *))completionHandler { 
    NSMutableURLRequest *newRequest = request.mutableCopy; 
    // Add authentication header here. 
    completionHandler(newRequest); 
} 

Authentication Header hinzuzufügen, wenn Ihre Anfrage umleiten wird.

3. Set Authentication Header als zusätzlicher Kopf Um NSURLSession

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 
config.HTTPAdditionalHeaders = @{@"Authorization":@"Basic xxxxxxxxxxxxxxxxxx"}; 
NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; 

Stellen Sie sicher, NSURLSession mit dem Authentication Header neue Anforderung erstellt.

Verwandte Themen