I have my own URLProtocol where I want to redirect all traffic through a proxy server.
My current working code is as follows:
+(BOOL)canInitWithRequest:(NSURLRequest*)request { if ([NSURLProtocol propertyForKey:protocolKey inRequest:request]) return NO; NSString *scheme = request.URL.scheme.lowercaseString; return [scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]; } -(void)startLoading { NSMutableURLRequest *request = self.request.mutableCopy; [NSURLProtocol setProperty:@YES forKey:protocolKey inRequest:request]; NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData; config.connectionProxyDictionary = @ { (id)kCFNetworkProxiesHTTPEnable:@YES, (id)kCFNetworkProxiesHTTPProxy:@"1.2.3.4", (id)kCFNetworkProxiesHTTPPort:@8080 }; m_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue currentQueue]]; [[m_session dataTaskWithRequest:request] resume]; }
It works great so far. The problem is that there is a URL that uses redirection - and I want the redirection to be done also by the proxy server, not the device. I tried to add the following code, but this did not help:
-(void)URLSession:(NSURLSession*)session task:(NSURLSessionTask*)task willPerformHTTPRedirection:(NSHTTPURLResponse*)response newRequest:(NSURLRequest*)newRequest completionHandler:(void (^)(NSURLRequest*))completionHandler { NSMutableURLRequest *request = newRequest.mutableCopy; [NSURLProtocol removePropertyForKey:protocolKey inRequest:request]; [self.client URLProtocol:self wasRedirectedToRequest:request redirectResponse:response]; [task cancel]; [self.client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]]; }
The problem is that a new request is not sent to the proxy server, but is redirected by the device itself.
Thanks.
source share