我无法找到一个内置的方式来解决这个问题,所以我创建了NSURLCache
,这递归HTTP如下类别重定向:
- (NSCachedURLResponse *)nf_cachedResponseForRequestByFollowingRedirects:(NSURLRequest *)request
{
NSCachedURLResponse *cachedResponse = [self cachedResponseForRequest:request];
NSHTTPURLResponse *HTTPURLResponse = (NSHTTPURLResponse *)cachedResponse.response;
if ([@[@301, @302, @303, @307, @308] containsObject:@(HTTPURLResponse.statusCode)])
{
NSString *redirectedURL = HTTPURLResponse.allHeaderFields[@"Location"];
if (redirectedURL.length > 0)
{
NSMutableURLRequest *redirectedRequest = request.mutableCopy;
redirectedRequest.URL = [NSURL URLWithString:redirectedURL];
return [self nf_cachedResponseForRequestByFollowingRedirects:redirectedRequest];
}
else
{
NSLog(@"Warning: got a redirected URL response, but without a 'Location' field to redirect to. Headers: %@", HTTPURLResponse.allHeaderFields);
return cachedResponse;
}
}
return cachedResponse;
}
注:该解决方案可能导致无限递归(和堆栈溢出)以防重定向循环。