2016-09-04 59 views
0

我搜索了所有在stackoverflow中可用的解決方案。仍然與此混淆。
請指出我是否有任何錯誤。我得到401錯誤。帶基本驗證挑戰的NSURLSession

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

可能想從問題 – Tibrogargan

+0

中刪除您的API密鑰謝謝。但很好。我試圖在PostMan中工作正常。我真的在想爲什麼它不起作用。 –

回答

0

也許你的輸出authValue包含新行後做base64,嘗試記錄字符串並刪除新行,否則標題將不會設置。

0

使用didReceiveAuthenticationChallenge方法,是在iOS中使用基本授權的正確方法。

請求:

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]; 

代表:

- (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

也許你的請求重定向到一些具有可由NSURLSession自動生成未經授權標頭的新要求還有什麼地方。

您可以使用Wireshark跟蹤您的請求發生的情況。

如果您的請求被重定向,您可以使用下面的方法,以確保新的請求與認證信息發送:

1.使用委託方法來處理身份驗證

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

應該是處理認證的最佳方式。

2.使用委託方法來認證頭添加到新要求

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

再次添加認證頭,當你要求得到重定向。

3.設置身份驗證頭作爲附加的頭要NSURLSession

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

確保NSURLSession創建與認證頭的新要求。