4

プロキシ サーバー経由ですべてのトラフィックをリダイレクトするカスタム URLProtocol があります。

私の現在の作業コードは次のようになります。

+(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];
}

これはこれまでのところうまくいきます。問題は、リダイレクトを使用する URL がいくつかあることです。デバイスではなく、プロキシ サーバーでもリダイレクトを実行する必要があります。次のコードを追加しようとしましたが、役に立ちませんでした。

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

問題は、新しいリクエストがプロキシ サーバーに送信されず、代わりにデバイス自体によってリダイレクトされることです。

ありがとう。

4

1 に答える 1