2015-02-06 93 views
3

我有一個自定義URLProtocol,我想通過代理服務器重定向所有流量。使用自定義NSURLProtocol和HTTP代理處理重定向

我當前工作的代碼看起來像這樣:

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

的問題是,新的請求沒有被髮送到代理服務器,而是由設備本身重定向。

謝謝。

+0

什麼是m_session在' - (空)startLoading'?你有可能發佈完整的URLProtocol文件嗎? – 2016-02-25 18:54:45

+1

@SamHeather m_session就是我保存NSURLSession實例的地方。有一個很好的教程(使用NSURLConnection代替),我用它作爲起點:http://www.raywenderlich.com/59982/nsurlprotocol-tutorial – 2016-02-25 21:25:50

+0

您是否有任何想法如何將connectionProxy應用於NSURLConnection或NSMutableURLRequest?尋找文檔觸摸缺乏這... – 2016-02-25 21:56:03

回答

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