更新时间:2023-12-03 11:22:34
也许您的请求通过NSURLSession自动生成的没有授权标头的新请求重定向到其他地方.
Perhaps your request is redirected to some where else with a new request which is auto-generated by NSURLSession without authorization header.
您可以使用Wireshark跟踪您的请求是否确实发生了.
You could use Wireshark to track your request exactly happened.
如果您的请求被重定向,则可以使用以下方法来确保新请求正在发送身份验证信息:
If your request is redirected, you can use the following methods to make sure the new request is sending with authentication information:
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);
}
}
应该是处理身份验证的***方法.
Should be best way to handle authentications.
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);
}
当您的请求被重定向时,再次添加身份验证标头.
Add authentication header again when your request gets redirect.
3.将身份验证标头设置为NSURLSession的附加标头
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPAdditionalHeaders = @{@"Authorization":@"Basic xxxxxxxxxxxxxxxxxx"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
确保NSURLSession使用该身份验证标头创建新请求.
Make sure NSURLSession creates new request with that authentication header.