使用自定义NSURLProtocol和HTTP代理处理重定向
问题描述:
我有一个自定义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]];
}
的问题是,新的请求没有被发送到代理服务器,而是由设备本身重定向。
谢谢。
答
事实证明,问题出在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
};
什么是m_session在' - (空)startLoading'?你有可能发布完整的URLProtocol文件吗? – 2016-02-25 18:54:45
@SamHeather m_session就是我保存NSURLSession实例的地方。有一个很好的教程(使用NSURLConnection代替),我用它作为起点:http://www.raywenderlich.com/59982/nsurlprotocol-tutorial – 2016-02-25 21:25:50
您是否有任何想法如何将connectionProxy应用于NSURLConnection或NSMutableURLRequest?寻找文档触摸缺乏这... – 2016-02-25 21:56:03