1. NSURLProtocol类
NSURLProtocol能够让你去重新定义苹果的URL加载系统 (URL Loading System)的行为,URL Loading System里有许多类用于处理URL请求,比如NSURL,NSURLRequest,NSURLConnection和NSURLSession等
可以拦截的网络请求包括NSURLSession,NSURLConnection以及UIWebVIew,基于CFNetwork的网络请求,以及WKWebView的请求是无法拦截的,WKWebView基于Webkit。
NSURLProtocol是一个抽象类,不能直接创建使用,需要继承使用,使用的时候需要调用registerClass:, [NSURLProtocol registerClass:[KCURLProtocol class]]
NSURLProtocol用处:
- 重定向网络请求(可以解决电信的DNS域名劫持问题)
- 忽略网络请求,使用本地缓存
- 自定义网络请求的返回结果Response
- 拦截图片加载请求,转为从本地文件加载
- 一些全局的网络请求设置
- 快速进行测试环境的切换
- 过滤掉一些非法请求
- 网络的缓存处理(H5离线包 和 网络图片缓存)
- 可以拦截UIWebView,基于系统的NSURLConnection或者NSURLSession进行封装的网络请求。目前WKWebView无法被NSURLProtocol拦截。
- 当有多个自定义NSURLProtocol注册到系统中的话,会按照他们注册的反向顺序依次调用URL加载流程。当其中有一个NSURLProtocol拦截到请求的话,后续的NSURLProtocol就无法拦截到该请求。
2. NSURLProtocol的使用主要是5个步骤:
- 注册
[NSURLProtocol registerClass:[KCURLProtocol class]];
- 拦截
NSURLConnection UIWebview请求拦截
+ (BOOL)canInitWithRequest:(NSURLRequest *)request;
NSURLSession的task拦截
+ (BOOL)canInitWithTask:(NSURLSessionTask *)task;
这两个方法是注册后,NSURLProtocol就会通过这个方法确定参数request、task是否需要被处理,YES需要被处理,NO不需要被处理,可以做重定向、监听
- 转发
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request;
通过该方法你可以简单的直接返回request,但可以在这里修改request,比如修改header,修改host等,并返回一个新的request,这是一个抽象方法,子类必须实现
- (void)startLoading;
把处理过的request重新发送出去
4.回调
这四个方法来回调给原来发送网络请求的地方。
[self.client URLProtocol:self didFailWithError:error];
[self.client URLProtocolDidFinishLoading:self];
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[self.client URLProtocol:self didLoadData:data];
- 结束
- (void)stopLoading;
[NSURLProtocol unregisterClass:[KCURLProtocol class]];
根据request从系统的缓存中构建protocol,没有缓存可能为nil,
- (instancetype)initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)cachedResponse client:(id<NSURLProtocolClient>)client
- (instancetype)initWithTask:(NSURLSessionTask *)task cachedResponse:(NSCachedURLResponse *)cachedResponse client:(id<NSURLProtocolClient>)client
处理过的请求可以通过为请求设置关联,下次不再处理,防止无限循环
+ (id)propertyForKey:(NSString *)key inRequest:(NSURLRequest *)request
+ (void)setProperty:(id)value forKey:(NSString *)key inRequest:(NSMutableURLRequest *)request
+ (void)removePropertyForKey:(NSString *)key inRequest:(NSMutableURLRequest *)request
判断2个请求是否相等,相等的话可以使用缓存数据
+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b
3. 拦截重定向演示
3.1 UIWebView 拦截
KCURLProtocol中:
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
// 拦截百度的logo
if ([[request.URL absoluteString] isEqualToString:@"https://m.baidu.com/static/index/plus/plus_logo_web.png"]) {
return YES;
}
return NO;
}
- (void)startLoading
{
// 拦截改成自己数据
if ([[self.request.URL absoluteString] isEqualToString:@"https://m.baidu.com/static/index/plus/plus_logo_web.png"]) {
NSString *fileName = [[NSBundle mainBundle] pathForResource:@"lufei.jpg" ofType:@""];
NSData *data = [NSData dataWithContentsOfFile:fileName];
[self.client URLProtocol:self didLoadData:data];//回调回去
}
}
3.2 NSURLSession 拦截
NSURLSession需要给NSURLSessionConfiguration对象的protocolClasses属性添加自己的协议,把系统的也加回去
- (void)startSessionHook
{
NSString *url = @"http://www.baidu.com";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:6];
[arr addObject:[NSClassFromString(@"KCURLProtocol") class]];
[arr addObjectsFromArray:config.protocolClasses];
config.protocolClasses = arr;
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:mainQueue];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
[dataTask resume];
}
+ (BOOL)canInitWithTask:(NSURLSessionTask *)task
{
NSLog(@"task---%@",task);
if ([task.originalRequest.URL.absoluteString isEqualToString:@"http://www.baidu.com"]) {
return YES;
}
return NO;
}
//转发
- (void)startLoading{
NSMutableURLRequest *request = [self.request mutableCopy];
if ([request.URL.absoluteString isEqualToString:@"http://www.baidu.com"]) {
request.URL = [NSURL URLWithString:@"https://www.jianshu.com/"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:mainQueue];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
[dataTask resume];
}
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
completionHandler(NSURLSessionResponseAllow);
}
//回调
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
// 打印返回数据
NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (dataStr) {
NSLog(@"***截取数据***: %@", dataStr);
}
[self.client URLProtocol:self didLoadData:data];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
if (error) {
[self.client URLProtocol:self didFailWithError:error];
} else {
[self.client URLProtocolDidFinishLoading:self];
}
}
3.3 AFN 拦截
AFN也是基于NSURLSession,我们可以新建一个NSURLSession的子类,在load方法里面hook protocolClasses的getter方法,这样所有的基于session的都能拦截测试实际上是hook __NSCFURLSessionConfiguration的getter方法,hook NSURLSessionConfiguration的getter不管用
+ (void)load
{
Class cls = NSClassFromString(@"__NSCFURLSessionConfiguration") ?: NSClassFromString(@"NSURLSessionConfiguration");
Method originalMethod = class_getInstanceMethod(cls, @selector(protocolClasses));
method_setImplementation(originalMethod, class_getMethodImplementation(self, @selector(my_protocolClasses)));
}
- (NSArray<Class> *)my_protocolClasses
{
NSMutableArray *arr = [[NSMutableArray alloc]initWithObjects:[NSClassFromString(@"KCURLProtocol") class], [NSClassFromString(@"_NSURLHTTPProtocol") class],[NSClassFromString(@"_NSURLDataProtocol") class],[NSClassFromString(@"_NSURLFTPProtocol") class],[NSClassFromString(@"_NSURLFileProtocol") class],[NSClassFromString(@"NSAboutURLProtocol") class],nil];
return arr;
}
4. 多个NSURLProtocol
如果注册了两个NSURLProtocol,protocols的遍历是反向的,也就是最后注册的protocol会被优先判断。