使用自定义NSURLProtocol和HTTP代理处理重定向

时间:2015-02-06 08:18:56

标签: ios redirect proxy nsurlprotocol

我有一个自定义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]];
}

问题是新请求没有发送到代理服务器,而是由设备本身重定向。

感谢。

1 个答案:

答案 0 :(得分:2)

事实证明,问题在于HTTPS服务器的重定向,而没有定义HTTPS代理。要使用HTTPS代理,代码应如下所示:

config.connectionProxyDictionary = @
{
    @"HTTPEnable":@YES,
    (id)kCFStreamPropertyHTTPProxyHost:@"1.2.3.4",
    (id)kCFStreamPropertyHTTPProxyPort:@8080,
    @"HTTPSEnable":@YES,
    (id)kCFStreamPropertyHTTPSProxyHost:@"1.2.3.4",
    (id)kCFStreamPropertyHTTPSProxyPort:@8080
};

来源:How to programmatically add a proxy to an NSURLSession