Ios 具有基本身份验证挑战的NSURLSession
我搜索了stackoverflow中所有可用的解决方案。仍然对此感到困惑。Ios 具有基本身份验证挑战的NSURLSession,ios,iphone,nsurlsession,Ios,Iphone,Nsurlsession,我搜索了stackoverflow中所有可用的解决方案。仍然对此感到困惑。 如果我做错了,请告诉我。我得到401错误 NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://qa.api.xxxxxx.com/v0/jobs/93033"]]; NSString *authStr = @"xxxxxxxx:xxxxxxxxxxx"; NSData
如果我做错了,请告诉我。我得到401错误
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];
在执行base64之后,authValue的输出可能包含新行,请尝试记录字符串并删除新行,否则不会设置标题。在执行base64之后,authValue的输出可能包含新行,请尝试记录字符串并删除新行,否则不会设置标头。使用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);
}
使用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);
}
您的请求可能会被重定向到其他地方,并带有一个新的请求,该请求由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);
}
}
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPAdditionalHeaders = @{@"Authorization":@"Basic xxxxxxxxxxxxxxxxxx"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
应该是处理身份验证的最佳方式
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的附加标头
- (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);
}
}
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPAdditionalHeaders = @{@"Authorization":@"Basic xxxxxxxxxxxxxxxxxx"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
确保NSURLSession使用该身份验证标头创建新请求。您的请求可能会被重定向到其他地方,而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);
}
}
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPAdditionalHeaders = @{@"Authorization":@"Basic xxxxxxxxxxxxxxxxxx"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
应该是处理身份验证的最佳方式
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的附加标头
- (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);
}
}
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPAdditionalHeaders = @{@"Authorization":@"Basic xxxxxxxxxxxxxxxxxx"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
确保NSURLSession使用该身份验证标头创建新请求。可能需要从问题中删除API密钥。谢谢。但是很好。我试过邮递员,效果很好。我真的在想为什么它不起作用。可能想从问题中删除API键。谢谢。但是很好。我试过邮递员,效果很好。我真的在想为什么它不起作用。